在更改状态下更改WPF文本框的背景颜色

oll*_*ant 6 data-binding wpf textbox background

我有一个EmployeeViewModel类,它有2个属性"FirstName"和"LastName".该类还有一个包含属性更改的字典.(该类实现了INotifyPropertyChanged和IDataErrorInfo,一切都很好.

在我看来,有一个文本框:

<TextBox x:Name="firstNameTextBox" Text="{Binding Path=FirstName}" />
Run Code Online (Sandbox Code Playgroud)

如果原始值发生变化,如何更改文本框的背景颜色?我想过创建一个触发器来设置背景颜色,但我应该绑定什么?我不想为每个控件创建一个额外的属性,该控件保持更改或不更改的状态.

谢谢

Bry*_*son 10

只需使用具有相同属性的MultiBinding两次,但在其中一个绑定上使用Mode = OneTime.像这样:

Public Class MVCBackground
    Implements IMultiValueConverter

    Public Function Convert(ByVal values() As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IMultiValueConverter.Convert
        Static unchanged As Brush = Brushes.Blue
        Static changed As Brush = Brushes.Red

        If values.Count = 2 Then
            If values(0).Equals(values(1)) Then
                Return unchanged
            Else
                Return changed
            End If
        Else
            Return unchanged
        End If
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetTypes() As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object() Implements System.Windows.Data.IMultiValueConverter.ConvertBack
        Throw New NotImplementedException()
    End Function
End Class
Run Code Online (Sandbox Code Playgroud)

在xaml中:

<TextBox Text="{Binding TestText}">
    <TextBox.Background>
        <MultiBinding Converter="{StaticResource BackgroundConverter}">
            <Binding Path="TestText"    />
            <Binding Path="TestText" Mode="OneTime" />
        </MultiBinding>
    </TextBox.Background>
</TextBox>
Run Code Online (Sandbox Code Playgroud)

不需要额外的属性或逻辑,您可以将它们全部包装到您自己的标记扩展中.希望有所帮助.