WPF转换器可在文本更改时实时更新文本框的背景色 [英] WPF converter to update in real time background colour of textbox on text change

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

问题描述

我有两个用于输入用户名和名字的文本框,并且我创建了一个转换器来在文本等于特定字符串时更改文本框的背景色。我遇到的问题是,文本框仅在运行时更新,而当我更改文本为文本框时不会更新。

I have two textboxes for the firstname and second name of a user and I have created a converter to change the background colour of the textbox when the text equals a specific string. The problem I am having is that the textbox will only update at run time and doesn't update when I change the text is the textbox.

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;
    }
}

正确的文本输入:

错误的文本输入-不变:

Wrong text input - no change:

推荐答案

您应该将画笔对象而不是颜色返回到背景,如下所示:

You should return some brush object than colors to background like below

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 new SolidColorBrush(Colors.Yellow);

    }
    else
    {
        return new SolidColorBrush(Colors.White);
    }
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
    return value;
}
}

这篇关于WPF转换器可在文本更改时实时更新文本框的背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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