Why can't I add a DataTrigger to my control's Triggers collection?

Tan picture Tan · Aug 26, 2010 · Viewed 39.6k times · Source

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>
</Border>

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.

Answer

Scott picture Scott · Aug 26, 2010

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>