C# WPF转换器在文本更改时实时更新文本框的背景颜色
我有两个文本框,分别代表一个用户的名字和第二个名字,我创建了一个转换器,当文本等于一个特定字符串时,可以更改文本框的背景颜色。我遇到的问题是,文本框只会在运行时更新,而在我更改文本框时不会更新 XAML: 正确的文本输入: 错误的文本输入-无更改:C# WPF转换器在文本更改时实时更新文本框的背景颜色,c#,wpf,xaml,converter,C#,Wpf,Xaml,Converter,我有两个文本框,分别代表一个用户的名字和第二个名字,我创建了一个转换器,当文本等于一个特定字符串时,可以更改文本框的背景颜色。我遇到的问题是,文本框只会在运行时更新,而在我更改文本框时不会更新 XAML: 正确的文本输入: 错误的文本输入-无更改: 您需要将UpdateSourceTrigger=PropertyChanged添加到您的绑定中: <TextBox x:Name="forenameTextBox" Grid.Column="1" HorizontalAlignment="L
您需要将
UpdateSourceTrigger=PropertyChanged
添加到您的绑定中:
<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"/>
这将在用户键入每个字母时更新绑定源。您可以在MSDN页面上找到更多信息。您应该返回一些笔刷对象,而不是背景颜色,如下所示
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;
}
}
首先,您将UpdateSourceTrigger=PropertyChanged
添加到了错误的绑定中。必须将其添加到文本
属性的绑定中
其次,您将Text
属性绑定到Staff.Forename
,而将Background
绑定到Staff
。Background
属性不知道在Staff.Forename
中写入时Staff
已更改。在写入Staff.Forename
属性时,必须为Staff
属性引发PropertyChanged
事件。对于员工也是一样。姓氏
我尝试过使用UpdateSourceRigger,但没有效果。我不太确定该告诉你什么。此属性符合您的要求。。。也许你应该在一个更简单的绑定上试试,或者阅读链接页面,自己看看。你的问题来自于员工没有收到更新通知的事实Staff.Forename
和Staff.Nastname
正在更新,但这并不自动意味着Staff
会更新。如果你在你的转换器中设置了一个断点,我想你会发现当你开始在文本框中输入时,它永远不会到达。您的转换器很好,问题在于文本框绑定到的数据。
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;
}
}