Textblock Style dataTrigger在ItemsControl中不起作用

akj*_*shi 2 .net wpf styles datatrigger itemscontrol

我有一个ObservableCollection<Object1>类型(Messages在下面的代码中)绑定到一个ItemsControl.Object1有两个属性即ErrMsgIsError.ErrMsg如果是错误(即如果IsError是),我想显示红色,否则显示黑色.

<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>
Run Code Online (Sandbox Code Playgroud)

问题是所有的消息总是以黑色显示而不管IsError价值如何?

我怎样才能做到这一点?

Pav*_*kov 8

那是因为你Foreground="Black"在文本块声明中指定了.本地值(在元素本身上设置)会覆盖样式值(包括触发器).

要解决此问题,只需将黑色前景的设置移动到样式:

<TextBlock Margin="5,0,0,0"
           Text="{Binding Value}"
           Width="Auto">
    <TextBlock.Style>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="Foreground"
                    Value="Black"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsError}"
                             Value="true">
                    <Setter Property="Foreground"
                            Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)