我怎样才能得到一个触发器来改变基于一个DataContext属性TextBlock的颜色? [英] How can I get a trigger to change the color of a TextBlock based on a DataContext Property?
问题描述
为什么下面的代码得到运行时错误:
触发器集合
成员必须是类型的EventTrigger的
块引用>
不过的EventTrigger元素没有一个绑定属性。
那么,如何改变?基于DataContext属性TextBlock的颜色
XAML:
<窗口x:类=TestTrigger123345.Window1
的xmlns =http://schemas.microsoft.com/winfx/2006/xaml/presentation
的xmlns:X =HTTP: //schemas.microsoft.com/winfx/2006/xaml
标题=窗口1HEIGHT =300WIDTH =300>
< StackPanel中的HorizontalAlignment =左>
< TextBlock的文本={绑定状态}>
< TextBlock.Triggers>
< DataTrigger绑定={绑定状态}VALUE =关>
< setter属性=TextBlock.BackgroundVALUE =红/>
< / DataTrigger>
< /TextBlock.Triggers>
< / TextBlock的>
< / StackPanel的>
< /窗GT;
代码:
命名空间TestTriggers
{
公共部分类窗口1:窗口
{
公共窗口1()
{
的InitializeComponent();
的DataContext =这一点;
状态=关;
}
公共字符串状态{搞定;组; }
}
}
解决方案那是因为你只能将事件直接触发触发属性。
使用样式来实现你想要什么:
<风格X:键=触发器的TargetType =TextBlock的>
< Style.Triggers>
< DataTrigger绑定={绑定状态}VALUE =关>
< setter属性=TextBlock.BackgroundVALUE =红/>
< / DataTrigger>
< /Style.Triggers>
< /样式和GT;
以下对象具有可以包含触发类型列出的触发器的集合:
FrameworkElement的样式,控件模板,DataTemplate中
---------------- ------- -----------------------------
的EventTrigger的EventTrigger
触发或MultiTrigger
DataTrigger或MultiDataTrigger
Why does the following code get the runtime error:
Members of the Triggers collection must be of type EventTrigger
But the EventTrigger element doesn't have a Binding property.
So how do I change the color of the TextBlock based on the DataContext Property?
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..
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
这篇关于我怎样才能得到一个触发器来改变基于一个DataContext属性TextBlock的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!