Visually Located


Migrating from the Windows Phone Toolkit ToggleSwitch to the new XAML ToggleSwitch

This is part of a series on migrating from the WP Toolkit.

The new Windows Phone 8.1 XAML SDK comes with new controls that previously were only in the Windows Phone Toolkit. One of these controls in the ToggleSwitch. The new ToggleSwitch control is really nice. The team has made some great improvements to this control.

Migrating to the new control is pretty easy. Along with all of the new controls, you no longer need to declare a namespace when using the control in XAML.

<!-- from -->
<!-- to -->

Instead of IsChecked, you’ll use the IsOn property.

<!-- from -->
<toolkit:ToggleControl IsChecked=”True/>
<!-- to -->
<ToggleControl IsOn=”True/>

The IsOn property is still a dependency property, so you can use binding as well.

<ToggleControl IsOn=”{Binding SomeSetting}”/>

The toolkit ToggleControl has built in Margins designed for use within a Phone app. The new XAML ToggleControl does not have any Margins defined. This is the case for all of the XAML controls. For a direct replacement you will have to add the margins in.

<ToggleControl Margin="9.5,5,9.5,33.6"/>

The new ToggleSwitch comes a few new properties. Four of these new properties allow you to control the “On” and ”Off” content. With the toolkit ToggleSwitch controlling the On/Off content was not that easy. The new OnContent and OffContent allow you to control the text to display when the switch is on or off. So if you wanted to display “true” and “false” you could do the following.

<ToggleSwitch OnContent=”trueOffContent=”false/>
image            image

The ToggleSwitch also comes with two properties for the template to use for the on and off content. If for some reason you wanted to display an image, you could set the templates to do just that.

<DataTemplate x:Key=”ImageToggleContent> 
    <Image Source=”{Binding}” Stretch="None"/> 
<!-- Other xaml -->
<ToggleSwitch OnContent=”Assets/On.pngOffContent=”Assets/Off.png
              OnContentTemplate=”{StaticResource ImageToggleContent}” 
              OffContentTemplate=”{StaticResource ImageToggleContent}”/> 

image            image 

Replacing the four previous events is one simple Toggled event. I like this change as it is the one stop location for being notified of state change. Having Checked, Unchecked, etc. events just adds bloat.

There you go, easy to move over to the new ToggleSwitch and you get some nice new features to boot!

blog comments powered by Disqus