简体   繁体   English

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

[英]WPF: How to change the Foreground color of a Textbox depending on the Text property of another in 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. 我想将WPF文本框的Foreground属性设为红色,只要其Text属性与表单上另一个Textbox的Text属性不匹配即可。 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? 但是,仅XAML有办法吗? (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}}"/>

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM