Defining DataTrigger for StackPanel
Asked Answered
S

2

18

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?

Sentinel answered 11/2, 2010 at 8:56 Comment(0)
D
19

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>
Distaste answered 11/2, 2010 at 9:28 Comment(0)
M
8

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>
Mittel answered 11/2, 2010 at 9:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.