在 Silverlight 中使用 IValueConverter 实现对绑定数据的格式化

转载:[url]http://www.cnblogs.com/driverpro/articles/1150836.html[/url]
在使用 Silverlight 对绑定数据进行展现的时候(如 ListBox、DataGrid),经常需要对数据的表现形式进行各式各样的处理,Silverlight 对绑定数据的格式化并不像 ASP.NET 中那么方便,在网上查了一些资料发现我们可以使用 IValueConverter 实现绑定数据的格式化。
下面我们用 ListBox 做一个例子:
首先我们先定义一个 MyTime 的类:

public class MyTime
{
public DateTime Time1 { get; set; }
public DateTime Time2 { get; set; }
}

放置一个 ListBox 并且设置绑定:

<ListBox x:Name="MyListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Time1}" Margin="5" Foreground="Red"></TextBlock>
<TextBlock Text="{Binding Time2}" Margin="5"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

创建一个 MyTime 的 List 并对其赋值:

List<MyTime> source = new List<MyTime>();
source.Add(new MyTime() { Time1 = DateTime.Now, Time2 = DateTime.Now });
MyListBox.ItemsSource = source;

运行结果如下,红色为 Time1,黑色为 Time2:

[img]http://dl.iteye.com/upload/attachment/166831/f7a20884-cffc-3c06-be8a-2abdd07393b5.jpg[/img]

下面我们对 Time1 进行格式化,使其只显示 年月日 ,首先我们先继承一个 IValueConverter 类,用于处理对时间的格式化:

using System.Windows.Data;
using System.Globalization;

public class DateTimeConverter: IValueConverter
{
public object Convert(object value,
Type targetType,
object parameter,
CultureInfo culture)
{
DateTime date = (DateTime)value;
return date.ToShortDateString();
}

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;
}
}

在 XAML 中注册空间命名并声明:

xmlns:local="clr-namespace:SilverlightDemo1"


<UserControl.Resources>
<local:DateTimeConverter x:Key="DateConverter" />
</UserControl.Resources>

最后修改 Time1 绑定数据的部分,加入格式化的内容:

<TextBlock Text="{Binding Time1, Converter={StaticResource DateConverter}}" Margin="5" Foreground="Red"></TextBlock>

运行看结果,是不是发现红色的 Time1 部分只现实年月日了呢:

[img]http://dl.iteye.com/upload/attachment/166836/aa58ebce-9bbb-3f95-bbc0-ebdc384191e8.jpg[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值