WPF:如何根据 XAML 中另一个文本框的文本属性更改文本框的前景色? [英] WPF: How to change the Foreground color of a Textbox depending on the Text property of another in XAML?

查看:27
本文介绍了WPF:如何根据 XAML 中另一个文本框的文本属性更改文本框的前景色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只要 WPF 文本框的 Text 属性与表单上另一个文本框的 Text 属性不匹配,我就想将 WPF 文本框的 Foreground 属性设为红色.我可以在后面的代码中并通过与转换器的绑定来完成此操作.但是有没有办法只在 XAML 中做到这一点?(我在想某种触发器).

I want to make the Foreground property of a WPF Textbox red as long as its Text property does not match the Text property of another Textbox on the form. I can accomplish this in the code behind and through a binding with a converter. But is there a way to do it in XAML only? (I was thinking of a Trigger of some kind).

推荐答案

不,您需要代码.该代码可能位于转换器中:

No, you need code. That code could be in a converter:

<TextBox x:Name="_textBox1"/>
<TextBox Foreground="{Binding Text, ElementName=_textBox1, Converter={StaticResource ForegroundConverter}}"/>

或者在视图模型中:

public string FirstText
{
    //get/set omitted
}

public string SecondText
{
    get { return _secondText; }
    set
    {
        if (_secondText != value)
        {
            _secondText = value;
            OnPropertyChanged("SecondText");
            OnPropertyChanged("SecondTextForeground");
        }
    }
}

public Brush SecondTextForeground
{
    get { return FirstText == SecondText ? Brushes.Red : Brushes.Black; }
}

这篇关于WPF:如何根据 XAML 中另一个文本框的文本属性更改文本框的前景色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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