.net WPF:如何根据 XAML 中另一个文本框的文本属性更改文本框的前景色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1353730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 13:14:37  来源:igfitidea点击:

WPF: How to change the Foreground color of a Textbox depending on the Text property of another in XAML?

.netwpfxaml

提问by Dabblernl

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).

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

回答by Kent Boogaart

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

不,你需要代码。该代码可能在转换器中:

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

Or in a view model:

或者在视图模型中:

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; }
}