WPF converter to update in real time background colour of textbox on text change

一笑奈何 提交于 2019-12-05 03:34:47

You need to add UpdateSourceTrigger=PropertyChanged to your Binding:

<TextBox x:Name="forenameTextBox" Grid.Column="1" HorizontalAlignment="Left" 
    Height="23" Margin="3" Grid.Row="1" Background="{Binding Staff, 
    UpdateSourceTrigger=PropertyChanged, Converter ={StaticResource 
    StaffNameToBackgroundColourConverter1}}" Text="{Binding Staff.Forename, 
    Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" 
    VerticalAlignment="Center" Width="120"/>

<TextBox x:Name="surnameTextBox" Grid.Column="1" HorizontalAlignment="Left" Height="23" 
    Margin="3" Grid.Row="2" Background="{Binding Staff, 
    UpdateSourceTrigger=PropertyChanged, Converter={StaticResource 
    StaffNameToBackgroundColourConverter1}}" Text="{Binding Staff.Surname, Mode=TwoWay, 
    NotifyOnValidationError=true, ValidatesOnExceptions=true}" 
    VerticalAlignment="Center" Width="120"/>

This will update the binding source as the user types each letter. You can find out more from the Binding.UpdateSourceTrigger Property page at MSDN.

You should return some brush object than colors to background like below

public class StaffNameToBackgroundColourConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo 
 culture)
{
    var staff = (Staff)value;
    if (staff.Forename == "Donald" && staff.Surname == "Duck")
    {
        return new SolidColorBrush(Colors.Yellow);

    }
    else
    {
        return new SolidColorBrush(Colors.White);
    }
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
    return value;
}
}
Mardukar

First, you added the UpdateSourceTrigger=PropertyChanged to the wrong binding. You have to add it to the binding of the Text property.

Second, you bound the Text property to Staff.Forename but the Background to Staff. The Background property doesn't know that Staff has changed when you write in Staff.Forename. You have to raise the PropertyChanged event for the Staff property when you write in the Staff.Forename property. Same for Staff.Surname.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!