在使用 Silverlight 对绑定数据进行展现的时候(如 ListBox、DataGrid),经常需要对数据的表现形式进行各式各样的处理,Silverlight 对绑定数据的格式化并不像 ASP.NET 中那么方便,在网上查了一些资料发现我们可以使用 IValueConverter 实现绑定数据的格式化。

     下面我们用 ListBox 做一个例子:

     首先我们先定义一个 MyTime 的类:
    
public class MyTime
{
    
public DateTime Time1 getset; }
    
public DateTime Time2 getset; }
}
 
     放置一个 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:


     下面我们对 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 部分只现实年月日了呢:


    
     以上部分资料来自网络,希望能够抛砖引玉,大家共同学习。
     以上Demo下载
posted on 2008-04-12 23:43  DRIVER.PRO  阅读(1906)  评论(0编辑  收藏  举报