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

Nig*_*sey 8 c# wpf xaml converter

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

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"/>
Run Code Online (Sandbox Code Playgroud)

转换器代码:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

正确的文字输入:

正确输入文字

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

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

She*_*dan 2

您需要添加UpdateSourceTrigger=PropertyChanged到您的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"/>
Run Code Online (Sandbox Code Playgroud)

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