【问题标题】:WPF: How to change the Foreground color of a Textbox depending on the Text property of another in XAML?WPF:如何根据 XAML 中另一个的 Text 属性更改文本框的前景色?
【发布时间】:2010-11-24 03:13:51
【问题描述】:

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

【问题讨论】:

    标签: .net wpf xaml


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,viewmodel 代码很有用,我以前从未遇到过这种模式。不过,我会选择转换器。
    猜你喜欢
    • 2018-08-08
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 2020-12-30
    • 2013-04-12
    • 2021-12-16
    • 2012-06-06
    • 2013-07-24
    相关资源
    最近更新 更多