使用IValueConverter类更改文本框的背景

时间:2019-03-30 07:33:45

标签: c#

你好,我有一个类可以根据其文本更改文本框的背景颜色。 如果文本为null,则其黄色,否则为透明。 但这是行不通的。

namespace Contrats_Congeles.Library
{
    [ValueConversion(typeof(string),typeof(SolidColorBrush))]
    public class BackgroundConverter_Yellow : IValueConverter
    {
            public Brush YellowBrush { get; set; }
            public Brush TransparentBrush { get; set; }

            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (value==null)
                {
                    return YellowBrush;
                }
                else
                {
                    return TransparentBrush;
                }
            }

            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }
    }
}

然后在XAML部分:

<Page.Resources>
    <local1:BackgroundConverter_Yellow x:Key="BackgroundConveter_Yellow"
                                       YellowBrush="Yellow"
                                       TransparentBrush="Transparent"/>
    <Style TargetType="{x:Type TextBox}">
        <Setter Property="Margin" Value="5"/>
        <Setter Property="CharacterCasing" Value="Upper"/>
    </Style>
    <Style TargetType="{x:Type DatePicker}">
        <Setter Property="Margin" Value="5"/>
    </Style>
    <Style TargetType="{x:Type ComboBox}">
        <Setter Property="Margin" Value="5"/>
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
    </Style>
    <Style TargetType="{x:Type GroupBox}">
        <Setter Property="Padding" Value="1"/>
        <Setter Property="BorderBrush" Value="Gray"/>
        <Setter Property="BorderThickness" Value="3"/>
        <Setter Property="Margin" Value="5"/>
    </Style>
</Page.Resources>

并在文本框中:

 <TextBox x:Name="PdsNetTxtBox" Grid.Row="1" Grid.Column="1"
                         PreviewKeyDown="PdsNetTxtBox_PreviewKeyDown"
                         Background="{Binding Path=Source,
                    Converter={StaticResource BackgroundConveter_Yellow}}"
                         KeyUp="PdsNetTxtBox_KeyUp"/>

但是,即使文本框的文本为空,也不会发生任何变化。 感谢您的帮助

2 个答案:

答案 0 :(得分:0)

您的错误来自测试值== null :(空与null不同)和您的绑定

我建议您添加字符串长度的测试

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //test the length of string
        if (value == null || value.ToString().Length == 0)
        {
            return YellowBrush;
        }
        else
        {
            return TransparentBrush;
        }
    }

这是我在TextBox中的绑定:

    <TextBox x:Name="PdsNetTxtBox" 
            Background="{Binding RelativeSource={RelativeSource self},Path=Text, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource BackgroundConveter_Yellow}}"/>

完整样本:

App.xaml:

<Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp1"
             StartupUri="MainWindow.xaml">
    <Application.Resources>

    </Application.Resources>
</Application>

MainWindow.xaml:

<Window x:Class="WpfApp1.MainWindow"                                                                                                                                              
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"                                                                                                         
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"                                                                                                                    
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"                                                                                                              
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"                                                                                                    
        xmlns:local="clr-namespace:WpfApp1"                                                                                                                                       
        xmlns:local1="clr-namespace:Contrats_Congeles.Library"                                                                                                                    
        mc:Ignorable="d"                                                                                                                                                          
        Title="MainWindow" Height="450" Width="800">                                                                                                                              
    <Window.Resources>                                                                                                                                                            
        <local1:BackgroundConverter_Yellow x:Key="BackgroundConveter_Yellow"                                                                                                      
                                          YellowBrush="Yellow"                                                                                                                    
                                          TransparentBrush="Transparent"/>                                                                                                        
    </Window.Resources>                                                                                                                                                           
    <Grid>                                                                                                                                                                        
        <TextBox x:Name="PdsNetTxtBox"                                                                                                                                            
                Background="{Binding RelativeSource={RelativeSource self},Path=Text, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource BackgroundConveter_Yellow}}"/>
    </Grid>                                                                                                                                                                       
</Window> 

Converter.cs:

using System;                                                                                                                                                                                                                                                                  
using System.Globalization;                                                                            
using System.Windows.Data;                                                                             
using System.Windows.Media;                                                                            

namespace Contrats_Congeles.Library                                                                    
{                                                                                                      
    [ValueConversion(typeof(string), typeof(SolidColorBrush))]                                         
    public class BackgroundConverter_Yellow : IValueConverter                                          
    {                                                                                                  

        public Brush YellowBrush { get; set; }                                                         
        public Brush TransparentBrush { get; set; }                                                    

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)    
        {                                                                                              

            if (value == null || value.ToString().Length == 0)                                         
            {                                                                                          
                return YellowBrush;                                                                    
            }                                                                                          
            else                                                                                       
            {                                                                                          
                return TransparentBrush;                                                               
            }                                                                                          
        }                                                                                              

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {                                                                                              
            throw new NotImplementedException();                                                       
        }                                                                                              
    }                                                                                                  
}                                                                                                      

答案 1 :(得分:0)

XAML:

<Page.Resources>
    <converterns:TextToBackgroundConverter x:Key="TextToBackgroundConverter"/>
</Page.Resources>

<TextBox Background="{Binding RelativeSource={RelativeSource Self}, Path=Text, Converter={StaticResource TextToBackgroundConverter}, Mode=OneWay}">

转换器类别:

public class TextToBackgroundConverter : IValueConverter {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
        string stringval = value.ToString();
        if(!string.IsNullOrEmpty(stringval)) return Brushes.Transparent;
        else return Brushes.Yellow;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
       return Binding.DoNothing;
    }
}

P.S。在手机上写

编辑:您可能要测试Text属性为空时的值。 'value'参数是null还是string.Empty。如果是string.Empty,则必须添加'if(value == null)return Binding.DoNothing;'。在Convert方法的开头