WPF Tutorial - How To Use A DataTemplateSelector
DataTemplateSelector可以让程序在runtime选择合适的DataTemplate
一般先从DataTempalteSelector类继承一个子类, 重写SelectTemplate方法
public class ImgStringTemplateSelector : DataTemplateSelector
{
public DataTemplate ImageTemplate { get; set; }
public DataTemplate StringTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
String path = (string)item;
String ext = System.IO.Path.GetExtension(path);
if (System.IO.File.Exists(path) && ext == ".jpg")
return ImageTemplate;
return StringTemplate;
}
}
<local:ImgStringTemplateSelector
ImageTemplate="{StaticResource imageTemplate}"
StringTemplate="{StaticResource stringTemplate}"
x:Key="imgStringTemplateSelector" />
然后,在控件中使用
<ListView ItemTemplateSelector="{StaticResource imgStringTemplateSelector}">
</ListView>