gpt4 book ai didi

c# - 数据触发器适用于 TextBox 但不适用于 TextBlock?

转载 作者:行者123 更新时间:2023-11-30 20:57:12 26 4
gpt4 key购买 nike

我有一些 DatTrigger 可以为 ListView 项设置文本颜色。如果我将 TextBox 用作 ListViewItemTemplate,它会完美运行。但如果我使用 TextBlock,它就不起作用。

这段代码:

<Style TargetType="TextBox">
<Style.Triggers>
<DataTrigger Binding="{Binding Level,Mode=OneWay}"
Value="{x:Static Common:LoggingLevel.Error}">
<Setter Property="Foreground"
Value="Red" />
</DataTrigger>
<DataTrigger Binding="{Binding Level,Mode=OneWay}"
Value="{x:Static Common:LoggingLevel.Warning}">
<Setter Property="Foreground"
Value="Orange" />
</DataTrigger>
</Style.Triggers>
</Style>

...

<ListView ItemsSource="{Binding Entries}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Text,Mode=OneWay}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

生成正确着色的消息列表。

虽然这段代码:

<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding Level,Mode=OneWay}"
Value="{x:Static Common:LoggingLevel.Error}">
<Setter Property="Foreground"
Value="Red" />
</DataTrigger>
<DataTrigger Binding="{Binding Level,Mode=OneWay}"
Value="{x:Static Common:LoggingLevel.Warning}">
<Setter Property="Foreground"
Value="Orange" />
</DataTrigger>
</Style.Triggers>
</Style>

...

<ListView ItemsSource="{Binding Entries}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Text,Mode=OneWay}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

使用默认的黑色前景色呈现所有消息。

最佳答案

隐式样式在模板中应用于继承自 System.Windows.Controls.Control 的元素自 TextBlock直接继承自 FrameworkElement它不会适用。要使其工作,您必须提供您的 Style x:Key并将样式明确分配给您的 TextBlock或在 TextBlock 中定义您的风格

更新:
我还应该提到,为了涵盖这个主题,有一种方法可以应用隐式 Style所有 TextBlocks .如果你把它放在Application.Resources它将适用于所有 TextBlocks在整个应用程序中。在这种情况下,它会导致一些主要的性能问题和潜在的其他错误,这可能是微软决定保护这些基本元素免于意外地使用复杂的隐式样式的原因。不是每个人都意识到基本上您在 Window 中看到的每段文字最终为 TextBlock .

关于c# - 数据触发器适用于 TextBox 但不适用于 TextBlock?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17003680/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com