Defining DataTrigger for StackPanel

stiank81 picture stiank81 · Feb 11, 2010 · Viewed 12.5k times · Source

How do I define a DataTrigger for a StackPanel? It does have a Trigger property, but defining a trigger here gives the following error on Initialize when starting the application:

Failed object initialization (ISupportInitialize.EndInit). Triggers collection members must be of type EventTrigger. ....

This is given from the following simple DataTrigger:

<StackPanel x:Name="PersonPanel" DataContext="{Binding CurrentPerson}">
    <TextBlock Text="{Binding Id}" />
    <TextBlock Text="{Binding Name}" />
    <StackPanel.Triggers>
        <DataTrigger Binding="{Binding Id}" Value="1">
            <Setter TargetName="PersonPanel" Property="StackPanel.Background" Value="Green" />
        </DataTrigger>                
    </StackPanel.Triggers>
</StackPanel>

This is my first Trigger ever, so what do I do wrong? Should I define the Trigger elsewhere?

Answer

Faisal picture Faisal · Feb 11, 2010

Try something like this

   <Window.Resources>
        <Style x:Key="spStyle" TargetType="StackPanel">
            <Setter Property="StackPanel.Background" Value="Red" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding Id}" Value="1">
                    <Setter Property="StackPanel.Background" Value="Green" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <StackPanel x:Name="PersonPanel" Style="{StaticResource spStyle}" DataContext="{Binding CurrentPerson}">
        <TextBlock Text="{Binding Id}" />
        <TextBlock Text="{Binding Name}" />
    </StackPanel>