C# 为什么这种简单的风格没有';你不申请吗?

C# 为什么这种简单的风格没有';你不申请吗?,c#,.net,wpf,xaml,styles,C#,.net,Wpf,Xaml,Styles,为什么TextBlock保持黑色 <Window x:Class="WpfApplication4.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="5

为什么TextBlock保持黑色

<Window x:Class="WpfApplication4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style TargetType="TextBlock" x:Key="style">
            <Style.Triggers>
                <DataTrigger Binding="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Tag}" Value="True">
                    <Setter Property="Foreground" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <StackPanel>
        <TextBlock Text="Test" Tag="True" Style="{StaticResource style}" />
    </StackPanel>
</Window>

TextBlock的文本会更改,但颜色不会将其更改为属性触发器

    <Style TargetType="TextBlock" x:Key="style">
        <Style.Triggers>
            <Trigger Property="Tag" Value="True">
                <Setter Property="Foreground" Value="Red" />
            </Trigger>
        </Style.Triggers>
    </Style>

在ControlTemplate中工作。您的绑定不正确。这就是它不起作用的原因

如果出于某种原因想使用DataTrigger,那么正确的绑定应该是

<DataTrigger Binding="{Binding Tag,RelativeSource={RelativeSource Self}}" Value="True">

只需更改绑定:

Binding="{Binding RelativeSource={RelativeSource Self}, Path=Tag}"

这主要是因为标记属性的类型是object而不是string。下面链接中给出的解决方案可能会帮助您:

关于Textblock.Tag属性:

我刚刚发现它可以与您建议的绑定一起使用,但不能与
触发器一起使用。看起来它试图比较布尔值和字符串,但总是返回false。请不要接受答案,然后用另一个问题更新问题。改为问一个新问题。
<DataTrigger Binding="{Binding Tag,RelativeSource={RelativeSource Self}}" Value="True">
Binding="{Binding RelativeSource={RelativeSource Self}, Path=Tag}"