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

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

问题描述

我有一个 EmployeeViewModel 类,它有 2 个属性FirstName"和LastName".该类还有一个包含属性更改的字典.(该类实现了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.

谢谢

推荐答案

只需使用具有相同属性的 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天全站免登陆