by brad
5. November 2010 06:00
Today’s tip focuses on the Toggle Switch that’s available in the Silverlight Toolkit for Windows Phone. If you’re not familiar with the Toolkit, check out the introductory post.
About the Toggle Switch
The toggle switch is a UI element that lets the user turn something on or off. One way to think of it is as the modern smartphone equivalent of a checkbox.
Using the Toggle Switch
To use the Toggle Switch, first add a reference to Microsoft.Phone.Controls.Toolkit.dll, which is installed with the toolkit.
Next, add a reference to the assembly in your page XAML
1: xmlns:toolbox="clr-namespace:Microsoft.Phone.Controls;
2: assembly=Microsoft.Phone.Controls.Toolkit"
The XAML
The XAML for the toggle switch is very simple
1: <toolkit:ToggleSwitch x:Name="FluxToggle"
2: Header="Flux Capacitor"
3: Checked="ToggleSwitch_Checked"
4: Unchecked="ToggleSwitch_Unchecked" />
This create a toggle switch that is labeled “Flux Capacitor”, has the standard On/Off choices, and is wired up with an event handler when it is checked or unchecked.
![CropperCapture[1] CropperCapture[1]](http://www.codebadger.com/blog/image.axd?picture=CropperCapture%5B1%5D.jpg)
The Code
You can read the current value of a ToggleSwitch with the IsChecked property
1: private void ToggleSwitch_Checked(object sender, RoutedEventArgs e)
2: {
3: MessageBox.Show(FluxToggle.IsChecked.ToString());
4: }
Changing the values
By default, the toggle switch uses “On” for true and “Off” for false. You can change this by setting the Content property of your control.
1: <toolkit:ToggleSwitch x:Name="FluxToggle"
2: Content="Fluxing" IsChecked="true"
3: Header="Flux Capacitor"
4: Checked="ToggleSwitch_Checked"
5: Unchecked="ToggleSwitch_Unchecked" />
The XAML above sets up a toggle switch that is checked and says “Fluxing”.
![CropperCapture[2] CropperCapture[2]](http://www.codebadger.com/blog/image.axd?picture=CropperCapture%5B2%5D_1.jpg)
To make sure that the custom labels stay in sync with the toggle switch, it’s just a matter of writing event handlers for Checked and Unchecked.
1: private void ToggleSwitch_Checked(object sender, RoutedEventArgs e)
2: {
3: FluxToggle.Content = "Fluxing";
4: }
5:
6: private void ToggleSwitch_Unchecked(object sender, RoutedEventArgs e)
7: {
8: FluxToggle.Content = "Not Fluxing";
9: }
![CropperCapture[3] CropperCapture[3]](http://www.codebadger.com/blog/image.axd?picture=CropperCapture%5B3%5D_1.jpg)
Other Resources
More Tips