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

I want the Foreground property of a WPF textbox to be red if its Text property doesn't match the Text property of another textbox on the form. I can accomplish this in the code behind and through the binding with the converter. But is there a way to do this in XAML only? (I was thinking about some kind of trigger).

+2


source to share


1 answer


No, you need a code. This code can be in the converter:

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

      



Or in the 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; }
}

      

+4


source







All Articles