tags:

views:

51

answers:

2
+2  Q: 

WPF Datatrigger

Why cant i code like this

<Border Width="130" Height="70">
<Border.Triggers>
    <DataTrigger Binding="{Binding Path=CurrentStatus}" Value="0">
        <Setter Property="Style" Value="{StaticResource ResourceKey=ListBoxItemBorder}"/>
    </DataTrigger>
    <DataTrigger Binding="{Binding Path=CurrentStatus}" Value="200">
        <Setter Property="Style" Value="{StaticResource ResourceKey=ListBoxItemBorderInactive}"/>
    </DataTrigger>
</Border.Triggers>

I get this error *Failed object initialization (ISupportInitialize.EndInit). Triggers collection members must be of type EventTrigger. Error at object '4_T' in markup file*

What am i doing wrong plz help.

+3  A: 

Unfortunately, only EventTriggers can be applied directly to elements. If you want to use a Trigger or DataTrigger, they have to be in a Style, ControlTemplate, or DataTemplate.

From the resource names, it looks like this is a Border inside a ListBoxItem ControlTemplate. You could easily move the triggers into the template's triggers collection.

Abe Heidebrecht
+4  A: 

Abe is correct and explains the limitations well. One thing you might want to consider is:

Instead of having two border styles, and trying to pick between them based on a trigger...

Use a single style on your border, this style's setters represent your 'normal' look. This style also contains your DataTrigger, and your DataTrigger has a collection of setters which essentially represents your second style (which have higher priority than the standard setters when this trigger evaluates to true!

Edit:

Something like this -

<Style TargetType="Border" x:Key="BorderStyle">
    <!-- These setters are the same as your normal style when none of your triggers are true -->
    <Setter Property="BorderBrush" Value="Black" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=CurrentStatus}" Value="0">
            <!-- These setters are the same as your ListBoxItemBorder style -->
            <Setter Property="BorderBrush" Value="Green" />
        </DataTrigger>
        <DataTrigger Binding="{Binding Path=CurrentStatus}" Value="200">
            <!-- These setters are the same as your ListBoxItemBorderInactive style -->
            <Setter Property="BorderBrush" Value="Gray" />
        </DataTrigger>
    </Style.Triggers>
</Style>
Scott