views:

298

answers:

2

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?

+2  A: 

try this:

<TextBlock Text="{Binding Id}">
    <TextBlock.Style>
        <Style>
            <Style.Triggers>
                <Trigger Property="TextBlock.Text" Value="1">
                    <Setter TargetName="PersonPanel" Property="StackPanel.Background" Value="Green" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>
Marcel Benthin
Thx! This works, but I went with Faisal's solution..
stiank81
You're welcome.
Marcel Benthin
+1  A: 

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>
Faisal
Thx! Works perfectly :-)
stiank81