WPF 值转换器 IValueConverter 例子

值转换器可以把一种类型转换成另一种类型。例如,绑定到一个代表图片地址的字符串,希望显示的是图片,将数据存储为浮点类型,但通过货币的形式呈现;还有将日期存储成DateTime格式,在界面上显示时使用Calender控件等。
下面写一个简单的例子,获得系统当前的时间,显示”now is 2010-xx-xx xx:xx;xx”。


xaml的代码:

<Window x:Class="VelueConverterTest.Window1"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       xmlns:local="clr-namespace:VelueConverterTest"
   Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <local:DateConverter x:Key="dateConverter"/>
    </Window.Resources>
    <Grid>
        <Label Margin="53,104,45,130" Name="label1" Content="{Binding Converter={StaticResource dateConverter}}"/>
    </Grid>
</Window>

XAML文件定义了一个dateConverter资源。指向CS文件中的DateConverter类。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Globalization;

namespace VelueConverterTest
{
    public partial class Window1 : Window
    {
        public DateTime nowtime { get; set; }
        public Window1()
        {
            InitializeComponent();
            nowtime = DateTime.Now;
            label1.DataContext = nowtime;
        }
    }

   //定义值转换器
    [ValueConversion(typeof(DateTime), typeof(String))]
    public class DateConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DateTime date = (DateTime)value;
            return "now is "+date.ToString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string strValue = value.ToString();
            DateTime resultDateTime;
            if (DateTime.TryParse(strValue, out resultDateTime))
            {
                return resultDateTime;
            }
            return value;
        }
    }
}

  


Convert和ConvertBack的区别:
Convert函数表示从数据源到目标的值转换,ConvertBack函数表示从目标到数据源的值转换。因此,如果绑定模式是一次绑定或单向 绑定,只需实现Convert函数;如果绑定模式是双向绑定,需要实现Convert和ConvertBack函数。

xaml中定义了label的Converter,当执行绑定的时候,WPF会把转换前的值,如本例中的nowtime 做为转换器函数Convert的输入值,将返回值显示在label控件上。

原文地址:https://www.cnblogs.com/babietongtianta/p/2701898.html