Textblock 样式 dataTrigger 在 ItemsControl 内不起作用
我有一个 ObservableCollection
类型(下面代码中的 Messages
),它绑定到 ItemsControl
。 Object1 有两个属性,即 ErrMsg
和 IsError
。如果错误(即,如果 IsError
为 true),我想以红色显示 ErrMsg
,否则显示黑色。
<ItemsControl
Height="Auto"
Background="White"
ItemsSource="{Binding Messages}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock
Margin="5,0,0,0"
Text="{Binding ErrMsg}"
Width="Auto"
Foreground="Black">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger
Binding="{Binding IsError}"
Value="true">
<Setter
Property="TextBlock.Foreground"
Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
问题是,无论 IsError
值如何,所有消息始终以黑色显示?
我怎样才能实现这个目标?
I have an ObservableCollection<Object1>
type(Messages
in code below) which is bound to an ItemsControl
. Object1 is having two properties namely ErrMsg
and IsError
. I want to display the ErrMsg
in red colour if its an Error(i.e. if IsError
is true) otherwise Black.
<ItemsControl
Height="Auto"
Background="White"
ItemsSource="{Binding Messages}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock
Margin="5,0,0,0"
Text="{Binding ErrMsg}"
Width="Auto"
Foreground="Black">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger
Binding="{Binding IsError}"
Value="true">
<Setter
Property="TextBlock.Foreground"
Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Problem is that all the messages are always displayed in Black colour irrespective of IsError
value?
How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为您在文本块声明中指定了
Foreground="Black"
。本地值(在元素本身上设置)覆盖样式值(包括触发器)。要解决此问题,只需将黑色前景的设置移至样式:
That's because you specify
Foreground="Black"
in your text block declaration. Local values (set on the element itself) override style values (including triggers).To fix this, just move setting of black foreground to the style:
我认为您只需要从属性中删除
TextBlock
前缀,并在样式中将前景设置为黑色:您通常只需要使用类型(应在括号中)来限定属性包含附加属性或故事板的路径。
I think you just need to remove the
TextBlock
prefix from your property, and set the foreground to black in the style:You typically only need to qualify the property with a type (which should be in parenthesis) for paths that include attached properties, or for storyboards.