WPF 绑定中Converter的应用

在WPF 经常用到绑定,如果绑定的源数据和目标属性是同类型的则不需要转换。比如

            <TextBox x:Name="txt1" Background="Blue" Text="测试"/>
            <TextBox Background="{Binding ElementName=txt1,Path=Background}" Grid.Column="1"/>
如果是不同类型的数据我们要怎么做呢?比如有一个文本框,一个按钮,我一个文本框里输入一个的数字用来代表颜色,1表示“红色”,2 表示“绿色”,3表示“蓝色”。我输入对应的数字,按钮的文字显示对应颜色。

显然这个不是同类型的数据:文本框的数据是String类型,而按钮的文字颜色是Brush类型,这个时候我们就需要用到转换器(converter)来告诉我们的banding怎么转换我们的数据。首先定义一个转换器(类),命名为Number2Color,要想实现转换的功能,必须实现IValueConverter接口中的Convert和ConvertBack两个函数。Convert函数是把我们的数据来源转换为目标数据的方法,这里就是把文本框里的string类型转换为Brush类型。我们这样实现Convert函数,(参数value就是数据来源的值,这里就是文本框中的数据,返回值就是Brush)

 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            int colorValue = System.Convert.ToInt32(value);
            switch (colorValue)
            {
                case 1:              //红色
                    return new SolidColorBrush(Colors.Red);

                case 2:               //绿色
                    return new SolidColorBrush(Colors.Green);
                case 3:               //蓝色
                    return new SolidColorBrush(Colors.Blue);

            }
            return new SolidColorBrush(Colors.LawnGreen);
        }


ConvertBak函数我们暂时先这样实现
       public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {

            return new NotImplementedException();
        }
现在来到xaml代码,显示一个文本框和一个按钮,并把按钮的前景色绑定到文本框的文本属性上,使用自定义的Number2Color转换器,运行程序  你修改文本框中的值,会看到按钮颜色发生变化。



<Window x:Class="Converter.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:cvt="clr-namespace:Converter"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
            <cvt:Number2Color x:Key="N2C"/>
    </Window.Resources>
    <Grid>

        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition Height="50"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="50"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBox x:Name="colorText" Text="1"  BorderBrush="Gray" BorderThickness="2" Width="200" Grid.Row="1"/>
        <Button x:Name="testBtn" Content="测试" Width="100" Grid.Row="3" FontSize="25" Foreground="{Binding Path=Text,ElementName=colorText, Converter={StaticResource N2C}}"/>
    </Grid>
</Window>


现在我们想实现如果按钮的文字颜色发生改变,文本框中的文字也对应改变。添加3个按钮,点击按钮的时候改变“测试”按钮的文字颜色。

<StackPanel Orientation="Horizontal">
            <Button Content="Red" Width="100" Foreground="Red" Click="btnClick"/>
            <Button Content="Green" Width="100" Foreground="Green" Click="btnClick"/>
            <Button Content="Blue" Width="100" Foreground="Blue" Click="btnClick"/>
 </StackPanel>
        private void btnClick(object sender, RoutedEventArgs e)
        {
            testBtn.Foreground = ((Button)sender).Foreground;
        }
运行程序,点击按钮,发现“测试”按钮文字颜色是改变了,但是文本框中的文字没有发生改变。这个和我们的绑定模式有关系,默认是单向绑定,我们应设置为双向绑定,我们为绑定增加属性:Mode=TwoWay

<Button x:Name="testBtn"  Content="测试" Width="100" Grid.Row="3" FontSize="25" Foreground="{Binding Path=Text,ElementName=colorText, Converter={StaticResource N2C}, Mode=TwoWay}"/>
此时运行程序,点击按钮发现,文字能变色,文本框内数字依然没有改变,而且按钮出现红色边框,提示错误。因为我们没有告诉程序怎么将Brush数据转换为文本数据,这正是ConvertBack要做的事情。我们之前在实现这个函数的时候是抛出一个异常,所有按钮会出现红色边框,表示不允许逆向转换。现在就让我们告诉程序怎么转换数据

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            SolidColorBrush sb = (SolidColorBrush)value;
            Color c = sb.Color;
           if (c==Colors.Red)
           {
               return 1;
           }
           else if (c == Colors.Green)
           {
               return 2;
           }
            else if (c==Colors.Blue)
            {
                return 3;
            }
            return 0;
        }

    }
这样就能实现双向绑定了。


转换器代码

namespace Converter
{
      public  class Number2Color:IValueConverter
      {
       public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            int colorValue = System.Convert.ToInt32(value);
            switch (colorValue)
            {
                case 1:              //红色
                    return new SolidColorBrush(Colors.Red);

                case 2:               //绿色
                    return new SolidColorBrush(Colors.Green);
                case 3:               //蓝色
                    return new SolidColorBrush(Colors.Blue);

            }
            return new SolidColorBrush(Colors.LawnGreen);
        }

       public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            SolidColorBrush sb = (SolidColorBrush)value;
            Color c = sb.Color;
           if (c==Colors.Red)
           {
               return 1;
           }
           else if (c == Colors.Green)
           {
               return 2;
           }
            else if (c==Colors.Blue)
            {
                return 3;
            }
            return 0;
        }

    }
}

前台代码

<Window x:Class="Converter.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:cvt="clr-namespace:Converter"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
            <cvt:Number2Color x:Key="N2C"/>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition Height="50"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="50"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBox x:Name="colorText" Text="1"  BorderBrush="Gray" BorderThickness="2" Width="200" Grid.Row="1"/>
        <Button x:Name="testBtn"  Content="测试" Width="100" Grid.Row="3" FontSize="25" Foreground="{Binding Path=Text,ElementName=colorText, Converter={StaticResource N2C}, Mode=TwoWay}"/>
        <StackPanel Orientation="Horizontal">
            <Button Content="Red" Width="100" Foreground="Red" Click="btnClick"/>
            <Button Content="Green" Width="100" Foreground="Green" Click="btnClick"/>
            <Button Content="Blue" Width="100" Foreground="Blue" Click="btnClick"/>
        </StackPanel>
    </Grid>
</Window>
按钮点击代码

        private void btnClick(object sender, RoutedEventArgs e)
        {
            testBtn.Foreground = ((Button)sender).Foreground;
        }



  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值