我有两个文本框用于输入用户的名字和姓氏,并且我创建了一个转换器,当文本等于特定字符串时更改文本框的背景颜色。但是我遇到的问题是,文本框只会在运行时更新,而当我更改文本框中的文本时,它不会更新。
XAML:
<TextBox x:Name="forenameTextBox" Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="3" Grid.Row="1"
Background="{Binding Staff,Converter ={StaticResource StaffNameToBackgroundColourConverter1}}"
Text="{Binding Staff.Forename, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" VerticalAlignment="Center" Width="120"/>
<Label Content="Surname:" Grid.Column="0" HorizontalAlignment="Left" Margin="3" Grid.Row="2" VerticalAlignment="Center"/>
<TextBox x:Name="surnameTextBox" Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="3" Grid.Row="2"
Background="{Binding Staff,Converter={StaticResource StaffNameToBackgroundColourConverter1}}"
Text="{Binding Staff.Surname, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" VerticalAlignment="Center" Width="120"/>
代码转换器:
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;
}
}
正确的文本输入:
错误的文本输入 - 没有更改:
Staff
没有被通知更新。Staff.Forename
和Staff.Surname
正在更新,但这并不意味着Staff
会自动更新。如果你在转换器中设置一个断点,我想当你开始在文本框中输入时,它永远不会被触发。你的转换器没问题,麻烦出现在你的文本框绑定的数据上。 - Stewbob