下面我们用 ListBox 做一个例子:
首先我们先定义一个 MyTime 的类:
public
class
MyTime
{
public DateTime Time1 { get; set; }
public DateTime Time2 { get; set; }
}
{
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 >
< 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;
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;
}
}
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 >
< local:DateTimeConverter x:Key ="DateConverter" />
</ UserControl.Resources >
最后修改 Time1 绑定数据的部分,加入格式化的内容:
<
TextBlock
Text
="
{Binding Time1, Converter={StaticResource DateConverter}}
"
Margin
="5"
Foreground
="Red"
></
TextBlock
>
运行看结果,是不是发现红色的 Time1 部分只现实年月日了呢:
以上部分资料来自网络,希望能够抛砖引玉,大家共同学习。
以上Demo下载