Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 994
Tan Avatar asked Aug 26 '10 14:08

Tan


2 Answers

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>
like image 76
Scott Avatar answered Oct 02 '22 14:10

Scott


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.

like image 23
Abe Heidebrecht Avatar answered Oct 02 '22 13:10

Abe Heidebrecht