Visually Located

XAML and GIS

Fixing the VisualState of your Win8 AppBar ToggleButton

This post would also be called Fixing the AppBarButtonStyle for ToggleButton support in you Win8 app: Part 2

In my last post I explained how to fix the AppBarButtonStyle to support ToggleButtons. This minor fix does give you the correct style, however there are more problems. I’m not sure if it is a problem with the style, or with the ToggleButton, but after checking and unchecking the button, the state becomes completely messed up.

image

When the ToggleButton does not have an AppBarButtonStyle set, it works great. We only get this problem when we apply one of those styles. With that said, it would seem there is a problem with the style, but the style looks just fine. I’ve seen some solutions that change the Unchecked and/or Normal VisualState back to the original style. I have not seen this working and this should happen by default. It appeared to me that the VisualState was actually getting messed up. I tried subscribing to the Click event and changing the VisualState manually.

void AppBarToggleButton_Click(object sender, RoutedEventArgs e)
{
    ToggleButton button = (ToggleButton)sender;
    VisualStateManager.GoToState(button, button.IsChecked.Value ? "Checked" : "Unchecked", false);
}

I was happy surprised to find that this worked great. Of course you do not want to subscribe to this event for every ToggleButton that you have. So I created a ToggleButton that would fix this (until MS fixes it).

public class AppBarToggleButton : ToggleButton
{
    public AppBarToggleButton()
    {
        this.Click += AppBarToggleButton_Click;
    }
 
    void AppBarToggleButton_Click(object sender, RoutedEventArgs e)
    {
        VisualStateManager.GoToState(this, IsChecked.Value ? "Checked" : "Unchecked", false);
    }
}

<sidenote>ToggleButton has a virtual OnToggle method that you would think would work great, however this method is called before the click event and before IsChecked changes.</sidenote>

blog comments powered by Disqus