WPF转换器在文本更改时实时更新文本框的背景颜色

我有两个文本框用于用户的名字和第二个名字,我创建了一个转换器,当文本等于特定字符串时,它会更改文本框的背景颜色。 我遇到的问题是文本框只会在运行时更新,并且在我更改文本时不会更新文本框。

XAML:

  

转换器代码:

 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 "Yellow"; } else { return "White"; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } } 

正确的文字输入:

正确的文字输入

错误的文字输入 – 没有变化:

错误的文字输入 - 没有变化

您需要将UpdateSourceTrigger=PropertyChanged添加到Binding

   

这将在用户键入每个字母时更新绑定源。 您可以从MSDN的Binding.UpdateSourceTrigger属性页面中找到更多信息。

首先,您将UpdateSourceTrigger=PropertyChanged添加到错误的绑定。 您必须将它添加到Text属性的绑定中。

其次,将Text属性绑定到Staff.Forename但将Background绑定到Staff 。 在Staff.Forename写入时, Background属性不知道Staff已更改。 在Staff.Forename属性中写入时,必须为Staff属性引发PropertyChanged事件。 Staff.Surname

您应该返回一些画笔对象而不是颜色到背景,如下所示

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