Mike
Mike

Reputation: 3284

Border Style Selector

I have 4 border elements in my xaml. My viewmodel has a state object which can be in state1, state2, state3, and state4. Based on the state, I need to draw my border with a particular background. For example if my state is state1, then border1 should have white background and the rest should be gray. If my state is state2, then border2 should be white, and the rest gray as so on.

I have defined 2 styles for this purpose, one wihich paints background with white and the other gray. Question is how do I do a style selection by specifying my bindings? Is there something called as a style selector available for Border element? Alternatively, how can I solve this issue?

Sample code:

  <Border Style="{StaticResource HighlightedTileStyle}" Grid.Column="0"/>
  <Border Style="{StaticResource NonHighlightedTileStyle}" Grid.Column="1"/>
  <Border Style="{StaticResource NonHighlightedTileStyle}" Grid.Column="2"/>
  <Border Style="{StaticResource NonHighlightedTileStyle}" Grid.Column="3"/>

<Style x:Key="HighlightedTileStyle" TargetType="{x:Type Border}">
 <Setter Property="Background" Value="White"/>
 </Style>

<Style x:Key="NonHighlightedTileStyle" TargetType="{x:Type Border}">
 <Setter Property="Background" Value="Gray"/>
 </Style>

Note that I have a viewmodel which has a state object called as IState, which can be of type State1, State2, State3 and State4.

Using .NET 3.5

Thanks, -Mike

Upvotes: 0

Views: 524

Answers (2)

Sheridan
Sheridan

Reputation: 69959

You can use some DataTriggers in the Style.Triggers collection for this:

<Style x:Key="BorderStyle" TargetType="{x:Type Border}">
    <Setter Property="Background" Value="Gray"/>
    <Style.Triggers>
        <DataTrigger Binding="{Binding State}" Value="1">
            <Setter Property="Background" Value="White" />
        </DataTrigger>
        ...
        <DataTrigger Binding="{Binding State}" Value="4">
            <Setter Property="Background" Value="Green" />
        </DataTrigger>
    </Style.Triggers>
</Style>

Of course, this assumes that the Border is used in a DataTemplate for the type of object that contains the State property, eg. assumes that this code has access to the State property.

Upvotes: 2

Victory Jessie
Victory Jessie

Reputation: 679

I think you can make use of triggers to achieve this. Refer below link for more details, http://msdn.microsoft.com/en-us/library/system.windows.trigger(v=vs.110).aspx

Upvotes: 0

Related Questions