In this article we will explore how to use ToggleSwitch in Windows Phone 7.ToggleSwitch is part of Microsoft.Phone.Controls.Toolkit.dll. ToggleSwitch has two states on or off which enables user to turn on or off any feature of Windows Phone 7.
Download Silverlight Windows Phone Toolkit
Let's write code to demonstrate how to use.
Step 1: Create a silverlight for Windows Phone project.
Step 2: Add reference of Microsoft.Phone.Controls.Toolkit.dll
Step 3: Add namespace of Microsoft.Phone.Controls.Toolkit in MainPage.xaml.
xmlns :toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
Step 4: Create instance of ToggleSwitch in MainPage.xaml
< toolkit:ToggleSwitch x:Name="toggle" Content="Switch is on" IsChecked="True" Header="ToggleSwitch"/>
Step 5: There are four important eventhandler of ToggleSwitch.
Checked event triggers when ToggleSwitch is checked.
Click event triggers when ToggleSwitch is clicked.
Indeterminate event trigger when ToggleSwitch indeterminate, neither on or off.
Unchecked event triggers when ToggleSwithc is unchecked.
Place below code in the constructor of the MainPage.
toggle.Checked += new EventHandler<RoutedEventArgs>(toggle_Checked); toggle.Click += new EventHandler<RoutedEventArgs>(toggle_Click); toggle.Indeterminate += new EventHandler<RoutedEventArgs>(toggle_Indeterminate); toggle.Unchecked += new EventHandler<RoutedEventArgs>(toggle_Unchecked);
Step 6: Place below code in the codebehind (MainPage.xaml.cs).
void toggle_Click(object sender, RoutedEventArgs e) { //Add code to execute when toggleswitch is clicked }
void toggle_Checked(object sender, RoutedEventArgs e) { toggle.Content = "Switch is On"; }
void toggle_Indeterminate(object sender, RoutedEventArgs e) { //Add code if toggleswitch is indeterminate state }
void toggle_Unchecked(object sender, RoutedEventArgs e) { toggle.Content = "Switch is Off"; }
Now run the application you will get the toggleswitch a shownbelow.

If you notice the color of the toggleswitch background when it is on is Red which is theme color. By default toggleswitch background will be theme color of the Windows Phone 7. You can change the color of toggleswitch background color using SwitchForeground color property of toggleswitch.
toggle.SwitchForeground = new SolidColorBrush(Colors.Orange);

One can change the background color of toggleswitch to green when it is on and red when it on.
To change the background color of toggleswitch to green when it on we need to add below line of code in toggle_Checked event.
toggle.SwitchForeground = new SolidColorBrush(Colors.Green);
To change the background color of toggleswitch to red when it off we need to add below line of code in toggle_Unchecked event.
toggle.SwitchForeground = new SolidColorBrush(Colors.Red);
This ends the article of Window Phone 7 - ToggleSwitch.
|