3

I have a button that has a style template in mode A. In mode A, this button has a PointerOver VisualState. I use the same button when I am in mode B, but in Mode B i'd like to have a different PointerOver VisualState.

What is the best way to get something like this done leveraging visual states? I am thinking having two different style templates for the same button and somehow changing which style template to use in code behind but not sure if this is possible or if this is the best way to approach this.

Any suggestions?

Gema Beltran
  • 171
  • 9

2 Answers2

2

Try this in your code behind:

[control name].Style = this.FindResource("[style key]") as Style;

Also you shouldn't call styles "style templates" as it can me misunderstood. Styles and templates are two different things.

  • Templates define how a given control is built. For example if a Button is built with use of a Border and a TextBlock (or with use some other controls).
  • Styles define a set of properties describing how does a given control look like (template is one of that properties).
1

Another option is to use a Converter to decide which Style the Button should be.

Converter:

public class ButtonStyleConverter : IValueConverter {
  public object Convert(object value, Type targetType, object parameter, string language)
  {
    var mode = (int)value;
    return mode == 1 ? Application.Current.Resources["ButtonStyle1"] as Style : Application.Current.Resources["ButtonStyle2"] as Style;
  }

  public object ConvertBack(object value, Type targetType, object parameter, string language)
  {
  //Do nothing
  }
}

Usage:

<Button Content="Hello" Style="{Binding Button1Mode, Converter={StaticResource ButtonStyleConverter}}"/>
<Button Content="World" Style="{Binding Button2Mode, Converter={StaticResource ButtonStyleConverter}}" />

I used aBinding to a property on my ViewModel, which in theory would allow you to modify the "Mode" the button is at runtime depending on Data. If you need more code on this I'd be happy to post an example on Github.

jsmyth886
  • 531
  • 7
  • 15