wpf值转换器IValueConverter--转载

原文地址:http://blog.163.com/wangzhenguo2005@126/blog/static/37140526201085113430862/

值转换器可以把一种类型转换成另一种类型。例如,绑定到一个代表图片地址的字符串,希望显示的是图片,将数据存储为浮点类型,但通过货币的形式呈现;还有将日期存储成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类。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Windows;
 6 using System.Windows.Controls;
 7 using System.Windows.Data;
 8 using System.Windows.Documents;
 9 using System.Windows.Input;
10 using System.Windows.Media;
11 using System.Windows.Media.Imaging;
12 using System.Windows.Navigation;
13 using System.Windows.Shapes;
14 using System.Globalization;
15 
16 namespace VelueConverterTest
17 {
18     public partial class Window1 : Window
19     {
20         public DateTime nowtime { get; set; }
21         public Window1()
22         {
23             InitializeComponent();
24             nowtime = DateTime.Now;
25             label1.DataContext = nowtime;
26         }
27     }
28 
29    //定义值转换器
30     [ValueConversion(typeof(DateTime), typeof(String))]
31     public class DateConverter : IValueConverter
32     {
33         public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
34         {
35             DateTime date = (DateTime)value;
36             return "now is "+date.ToString();
37         }
38 
39         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
40         {
41             string strValue = value.ToString();
42             DateTime resultDateTime;
43             if (DateTime.TryParse(strValue, out resultDateTime))
44             {
45                 return resultDateTime;
46             }
47             return value;
48         }
49     }
50 } 

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

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

posted @ 2012-09-21 16:18  Lyghost  阅读(663)  评论(7编辑  收藏  举报