更改状态为WPF文本框的更改背景色 [英] Change Background Color for WPF textbox in changed-state

查看:374
本文介绍了更改状态为WPF文本框的更改背景色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a class EmployeeViewModel with 2 properties "FirstName" and "LastName". The class also has a dictionary with the changes of the properties. (The class implements INotifyPropertyChanged and IDataErrorInfo, everything is fine.

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

In my view there is a textbox:

<TextBox x:Name="firstNameTextBox" Text="{Binding Path=FirstName}" />

如果原始值更改了,如何更改文本框的背景颜色?我曾考虑过创建一个设置背景颜色的触发器,但是该绑定到什么呢? 我不想为每个控件创建一个额外的属性,而无论控件是否被更改,该控件都会保持状态.

How can I change the background color of the textbox, if the original value changed? I thought about creating a trigger which sets the background color but to what should I bind? I don't want to created an additional property for every control which holds the state wheter the one was changed or not.

Thx

推荐答案

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

Just use a MultiBinding with the same property twice but have Mode=OneTime on one of the bindings. Like this:

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

在xaml中:

<TextBox Text="{Binding TestText}">
    <TextBox.Background>
        <MultiBinding Converter="{StaticResource BackgroundConverter}">
            <Binding Path="TestText"    />
            <Binding Path="TestText" Mode="OneTime" />
        </MultiBinding>
    </TextBox.Background>
</TextBox>

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

No extra properties or logic required and you could probably wrap it all into your own markup extension. Hope that helps.

这篇关于更改状态为WPF文本框的更改背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆