一、概述
DataTemplate顾名思义,就是数据模板,用来指定数据的表现形式。这对于ItemsControl类的控件尤其有用,可以改变列表项的外观,更具有表现能力。
二、实例
View Code
上例中通过指定ListBox.ItemTemplate属性来定义子项的显示格式,如果不是列表项,可以通过控件的ContentTemplate属性来指定应用哪个数据模板。
使用起来比较简单,大概分为三步:
1.如果有些属性不是可以直接使用,需要转换的,写转换器,实现IValueConverter接口
2.定义好转换器之后,需要实例化,指定给需要的绑定
3.定义模板,也就是需要的显示格式
4.应用模板,把定义好的模板指定到目标控件的ContentTemplate或者ItemTemplate
看一个完整的例子
1.用来封装的实体类和转换器
View Code
class Car
{
public string Automaker { get; set; }
public string Name { get; set; }
public string Year { get; set; }
public string TopSpeed { get; set; }
}
//厂商名称转化为Logo图片
public class AutomakerToLogoPathConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string uriStr = string.Format(@"images/{0}.jpg",value.ToString());
return new BitmapImage(new Uri(uriStr, UriKind.Relative));
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
//汽车名称转化为图像
public class NameToPhotoPathConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string uriStr = string.Format(@"images/{0}.jpg", value.ToString());
return new BitmapImage(new Uri(uriStr, UriKind.Relative));
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
2.模板及窗体
View Code
3.指定数据源
View Code
private void InitialCarList()
{
List cars = new List()
{
new Car(){ Automaker="CADILLAC",Name="CADILLAC1",Year="1990",TopSpeed="340"},
new Car(){ Automaker="Ferrari",Name="Ferrari1",Year="1991",TopSpeed="350"},
new Car(){ Automaker="LAMBORGHINI",Name="LAMBORGHINI1",Year="1992",TopSpeed="360"},
new Car(){ Automaker="PORSCHE",Name="PORSCHE1",Year="1993",TopSpeed="370"}
};
this.listBoxCars.ItemsSource = cars;
}
三、实例下载
https://download.csdn.net/download/qq_30725967/86507116