WPF值转换器

25 篇文章 8 订阅

一、摘要

本文通过实例演示WPF值转换器的应用,并在演示过程中,对WPF值转换器的相关知识点进行解释说明。

 

二、实例演示

1 新建WPF应用程序ConverterExp,程序结构如下图所示。

 

图1 程序结构图

程序的主画面如下图所示。

 

图2 程序主画面

程序完成功能:

通过改变画面中ComboBox控件的选中项来改变TextBlock控件的Background值。

ComboBox控件的下拉列表中可供选择的项有“red”“green”和“blue”,默认选中的项为“red”。

TextBlock控件默认Background值为red


2 新建值转换器类ColorConverter,类文件名为ColorConverter.cs

WPF的绑定模型中,可以使用值转换器将值从一种类型转换成另外一种类型。

本例中的值转换器ColorConverter将整型数据转换成SolidColorBrush类型数据。

SolidColorBrush类型表示纯色的画刷,将SolidColorBrush类型的实例与TextBlock控件的Background属性绑定后,就可以设置TextBlock控件的背景色。

ColorConverter类的详细代码如下所示。

//************************************************************
//
// IValueConverter接口示例代码
//
// Author:三五月儿
// 
// Date:2014/08/03
//
// http://blog.csdn.net/yl2isoft
//
//************************************************************
using System;
using System.Windows.Data;
using System.Windows.Media;
 
namespace ConverterExp
{
    public class ColorConverter : IValueConverter
    {
        public static Color[] ColorCollection = new Color[] {
                                                    Color.FromRgb(255,0,0),//red
                                                    Color.FromRgb(0,255,0),//green
                                                    Color.FromRgb(0,0,255)//blue
                                                };
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
            {
                return new SolidColorBrush(ColorCollection[0]);
            }
            try
            {
                return new SolidColorBrush(ColorCollection[(int)value]);
            }
            catch (Exception) 
            { 
                return new SolidColorBrush(ColorCollection[0]); 
            }
        }
 
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
与绑定进行关联的值转换器必须 实现接口 IValueConverter IValueConverter 接口包含 Convert ConvertBack 方法的定义,所以,值转换器都必须实现 Convert ConvertBack 方法

ConvertConvertBack方法的区别Convert方法表示从绑定数据源到绑定目标的值转换,ConvertBack方法表示从绑定目标到绑定数据源的值转换。因此,如果绑定模式是一次性绑定或单向绑定,只需要在Convert方法的实现中完成值转换的工作即可;如果是双向绑定,需要同时在ConvertConvertBack方法的实现中完成值转换的工作

本例中的绑定模式是单向绑定,所以,仅需要在Convert方法的实现中完成值转换的工作,而在ConvertBack方法的实现中,除了抛出NotImplementedException异常外,不用完成任何其他工作。

实例中ColorConverter类的Convert方法,一开始会将传入的value与null进行对比,若value为null,则使用ColorCollection中的第一个颜色值来初始化SolidColorBrush对象并返回;若value不为null,则将value强制转换为整型,并用转换后的整型值作为索引在ColorCollection中获取颜色值来初始化SolidColorBrush对象并返回;方法中若出现异常,则同样使用ColorCollection中的第一个颜色值来初始化SolidColorBrush对象并返回。

 

3 新建ConverterViewModel类,类文件名为ConverterViewModel.cs

在ConverterViewModel类中,定义了程序主画面用到的数据源。

详细的代码如下所示。

//************************************************************
//
// IValueConverter接口示例代码
//
// Author:三五月儿
// 
// Date:2014/08/03
//
// http://blog.csdn.net/yl2isoft
//
//************************************************************
using System.Collections.Generic;
 
namespace ConverterExp
{
    public class ConverterViewModel
    {
        public IList<ColorInfo> ColorList { get; set; }
        public int SelectedColor { get; set; }
        public ConverterViewModel()
        {
            ColorList = new List<ColorInfo>()
            {   
                new ColorInfo(){ ID=0, Name="red"},
                new ColorInfo(){ ID=1, Name="green"},
                new ColorInfo(){ ID=2, Name="blue"}
             };
            SelectedColor = 0;
        }
    }
    public class ColorInfo
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
}
其中,ColorList 属性 于指定ComboBox控件下拉列表的选择项(一个ColorInfo实例代表一个选择项),SelectedColor 属性用于指定 ComboBox 控件的被选中项。

 

4 程序主画面的实现

4.1 MainWindow.xaml

<Window x:Class="ConverterExp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:localUtil="clr-namespace:ConverterExp"
        Title="Converter演示程序" Height="350" Width="525" WindowStyle="ToolWindow">
    <Grid>
        <Grid.Resources>
            <localUtil:ColorConverter x:Key="ColorConverter"/>
        </Grid.Resources>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition ></ColumnDefinition>
            <ColumnDefinition ></ColumnDefinition>
            <ColumnDefinition ></ColumnDefinition>
            <ColumnDefinition ></ColumnDefinition>
            <ColumnDefinition ></ColumnDefinition>
            <ColumnDefinition ></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Label Content="颜色:" Grid.Row="3" Grid.Column="1" Margin="45,7,0,7"/>
        <TextBlock Background="{Binding SelectedValue,ElementName=ComboBox_ColorSelect,Converter={StaticResource ColorConverter}}" Grid.Row="3" Grid.Column="2" Height="25" Width="80" Margin="0,7,0,7"></TextBlock>
        <ComboBox Cursor="Hand" x:Name="ComboBox_ColorSelect" Height="25" Width="80" ItemsSource="{Binding ColorList}" SelectedValuePath="ID"  DisplayMemberPath="Name" SelectedValue="{Binding SelectedColor}" Grid.Row="3" Grid.Column="3"  Margin="0,7,0,7"></ComboBox>
    </Grid>
</Window>

4.2 MainWindow.xaml.cs

//************************************************************
//
// IValueConverter接口示例代码
//
// Author:三五月儿
// 
// Date:2014/08/03
//
// http://blog.csdn.net/yl2isoft
//
//************************************************************
using System.Windows;
namespace ConverterExp
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new ConverterViewModel();
        }
    }
}

MainWindow.xaml.cs的代码中,通过代码“this.DataContext = new ConverterViewModel()”设置主画面绑定数据源

MainWindow.xaml文件中的以下内容与文章主题有关,下面将对此部分内容做重点说明。

<TextBlock Background="{Binding SelectedValue,ElementName=ComboBox_ColorSelect,Converter={StaticResource ColorConverter}}" Grid.Row="3" Grid.Column="2" Height="25" Width="80" Margin="0,7,0,7"></TextBlock>
<ComboBox Cursor="Hand" x:Name="ComboBox_ColorSelect" Height="25" Width="80" ItemsSource="{Binding ColorList}" SelectedValuePath="ID"  DisplayMemberPath="Name" SelectedValue="{Binding SelectedColor}" Grid.Row="3" Grid.Column="3"  Margin="0,7,0,7"></ComboBox>

通过阅读代码,可以了解到:

数据源中的ColorList属性与ComboBox的ItemsSource属性绑定,使ComboBox的下拉列表框中包含选择项“red”“green”和“blue”;

数据源中的SelectedColor属性与ComboBox的SelectedValue属性绑定,SelectedColor初始化时被赋值为0,表示ComboBox默认选中的为第一项,值为“red”;

ComboBox的SelectedValuePath属性与ColorInfo实例的ID属性绑定,ComboBox的DisplayMemberPath属性与ColorInfo实例的Name属性绑定,这样一来,当更改ComboBox的选中项时,SelectedValue属性将保存选中项的ID,而在画面中显示的是选中项的Name。

TextBlock控件的Background属性与ComboBox控件的SelectedValue属性绑定。这样一来,当ComboBox控件中被选中的项发生改变时,TextBlock控件的Background值也会一起发生变化。例如:ComboBox控件被选中的颜色为“red”时,则ComboBox控件的SelectedValue属性值为0,从而TextBlock控件的Background属性的绑定值就为0;当ComboBox控件被选中的颜色为“green”时,则ComboBox控件的SelectedValue属性值为1,从而TextBlock控件的Background属性的绑定值就为1。与此同时,使用值转换器完成值的转换工作,当Background的值变为0时,值转换器会将0转换成相应的SolidColorBrush对象,并使用转换后的SolidColorBrush对象来完成绑定操作。

 

三 总结

WPF的绑定中,可以使用值转换器将值从一种类型转换成另外一种类型。

值转换器必须实现IValueConverter接口的Convert和ConvertBack方法。

 

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值