如何获得触发器以根据 DataContext 属性更改 TextBlock 的颜色? [英] How can I get a trigger to change the color of a TextBlock based on a DataContext Property?

查看:42
本文介绍了如何获得触发器以根据 DataContext 属性更改 TextBlock 的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码会出现运行时错误:

Why does the following code get the runtime error:

Triggers 集合的成员必须是 EventTrigger 类型

Members of the Triggers collection must be of type EventTrigger

但 EventTrigger 元素没有 Binding 属性.

But the EventTrigger element doesn't have a Binding property.

那么如何根据 DataContext 属性更改 TextBlock 的颜色?

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>

代码:

namespace TestTriggers
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            DataContext = this;
            Status = "off";
        }

        public string Status { get; set; }    
    }
}

推荐答案

那是因为你只能直接在Trigger属性上设置事件触发器..

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆