[英]How can I get a trigger to change the color of a TextBlock based on a DataContext Property?
Why does the following code get the runtime error: 为什么以下代码会出现运行时错误:
Members of the Triggers collection must be of type EventTrigger Triggers集合的成员必须是EventTrigger类型
But the EventTrigger element doesn't have a Binding property. 但EventTrigger元素没有Binding属性。
So how do I change the color of the TextBlock based on the DataContext Property? 那么如何根据DataContext属性更改TextBlock的颜色?
XAML: XAML:
<Window x:Class="TestTrigger123345.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel HorizontalAlignment="Left">
<TextBlock Text="{Binding Status}">
<TextBlock.Triggers>
<DataTrigger Binding="{Binding Status}" Value="off">
<Setter Property="TextBlock.Background" Value="Red"/>
</DataTrigger>
</TextBlock.Triggers>
</TextBlock>
</StackPanel>
</Window>
Code: 码:
namespace TestTriggers
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
DataContext = this;
Status = "off";
}
public string Status { get; set; }
}
}
That is because you can only set event triggers directly on the Trigger property.. 那是因为您只能直接在Trigger属性上设置事件触发器。
Use a style to achieve what you want: 使用样式来实现您想要的效果:
<Style x:Key="Triggers" TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding Status}" Value="off">
<Setter Property="TextBlock.Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
The following objects have Triggers collections that can contain the trigger types listed: 以下对象具有可包含列出的触发器类型的触发器集合:
FrameworkElement Style, ControlTemplate, DataTemplate
---------------- ------------------------------------
EventTrigger EventTrigger
Trigger or MultiTrigger
DataTrigger or MultiDataTrigger
You can do it in a style: 你可以用一种风格来做:
<TextBlock Text="{Binding Status}">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding Status}" Value="off">
<Setter Property="Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
There is a typo as you did not close out Style.Triggers. 你没有关闭Style.Triggers有一个错字。 And I found I needed to use the property TextBlock.Background. 我发现我需要使用属性TextBlock.Background。 Thanks, you got me to the solution. 谢谢,你帮我解决了。
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding Status}" Value="off">
<Setter Property="TextBlock.Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.