Change foreground color of textbox when text changes and meets certain criterion

Aarohi S picture Aarohi S · Jun 7, 2013 · Viewed 10.2k times · Source

I require to set text color when text changes inside textbox and meets certain criterion. I can implement this from code behind with textbox_textchanged event and set brushes.color to desired color.

But I am not being able to implement this with xaml wpf approach. I am new to wpf, I'm not sure how can I set text color depending upon certain criterion when text changes in textbox.

For example: For a given textbox, when text changes, it needs to determine if input text is a number then change foreground color to green else red.

Looking forward for the help. Thank you in advance.

Answer

Colin picture Colin · Jun 7, 2013

I am not sure whether a binding converter is allowed in your situation. But here is a solution which only needs a binding converter in your code behind.

Here is the code in xaml

    <Grid.Resources>
        <local:ValueConverter x:Key="ValueConverter"></local:ValueConverter>
    </Grid.Resources>
    <TextBox Text="{Binding Text,UpdateSourceTrigger=PropertyChanged}">
        <TextBox.Style>
            <Style>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=Text,Converter={StaticResource ValueConverter}}" Value="True">
                        <Setter Property="TextBox.Foreground" Value="Red"></Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>

Here is the view model and the value converter

public class ViewModel : INotifyPropertyChanged
{
    private string _text;

    public string Text
    {
        get
        {
            return this._text;
        }
        set
        {
            this._text = value;
            if (null != PropertyChanged)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs("Text"));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

public class ValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (null != value)
        {
            if (value.ToString() == "1")
                return true;
        }
        return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }
}

So the solution uses the data trigger to fulfill the goal. The only reason for using binding converter here is that you need a place to determine what kind of value should change the foreground of the TextBox. Here the foreground of TextBox will be red when the value of the TextBox is "1".