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