wpf值转换器IValueConverter例子

wpf值转换器IValueConverter例子

No Comments »

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

1
2
3
4
5
6
7
8
9
10
11
12
<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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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控件上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值