为StackPanel定义DataTrigger

时间:2010-02-11 08:56:12

标签: .net wpf triggers datatrigger stackpanel

如何为DataTrigger定义StackPanel?它确实具有Trigger属性,但是在此处定义触发器会在启动应用程序时在Initialize上出现以下错误:

  

对象初始化失败(ISupportInitialize.EndInit)。触发器集合成员必须是EventTrigger类型。 ....

这是从以下简单的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>

这是我的第一个Trigger,所以我做错了什么?我应该在其他地方定义Trigger吗?

2 个答案:

答案 0 :(得分:13)

尝试这样的事情

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

答案 1 :(得分:7)

试试这个:

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