Using the ToggleSwitch

,

Like the ToggleButton, ToggleSwitch uses a nullable Boolean value to represent its state. In its On position, its IsChecked property is true. In the Off position, IsChecked is false. If the IsChecked property is null, the ToggleSwitch is displayed using its Off position.

You can use the ToggleSwitch by either binding its IsChecked property to a property in your viewmodel, or by responding to its Checked and Unchecked events in your code-beside. The later approach involves subscribing to the ToggleSwitch.Checked and Unchecked events, as shown:

<toolkit:ToggleSwitch
        Header="ToggleSwitch"
        IsChecked="true"
        Checked="ToggleSwitch_Checked"
        Unchecked="ToggleSwitch_Unchecked"/>

Both the Checked and Unchecked events are RoutedEvents. The following excerpt shows what event handlers for these events might look like:

void ToggleSwitch_Checked(object sender, RoutedEventArgs e)
{
    ToggleSwitch toggleSwitch = (ToggleSwitch)sender;
    bool? isChecked = toggleSwitch.IsChecked;
    /* Do something with value. */
    MessageBox.Show("Checked!");
}

void ToggleSwitch_Unchecked(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Unchecked!");
}

ToggleSwitch allows customization of its header using its Header and HeaderTemplate properties. For more information on creating a custom header for the control, see the previous section “Adding a Control Header.”

Binding the ToggleSwitch to a Viewmodel Property

Rather than placing UI logic in the code-beside, an alternative is to bind the ToggleSwitch to a viewmodel property. This is demonstrated in the ToggleSwitchView and ToggleSwitchViewModel, in the downloadable sample code.

The viewmodel contains a ToggleOn property, as shown:

bool? toggleOn;

public bool? ToggleOn
{
    get
    {
        return toggleOn;
    }
    set
    {
        Assign(ref toggleOn, value);
    }
}

Consuming this property in the view is a ToggleSwitch, whose IsChecked property has a two-way data binding to the ToggleOn property of the viewmodel:

<toolkit:ToggleSwitch
    Header="ToggleSwitch"
    IsChecked="{Binding ToggleOn, Mode=TwoWay}" />

Thus, when the user taps the ToggleSwitch, the ToggleOn property of the viewmodel is inverted.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.255.113