如何为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
吗?
答案 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>