mrfangzheng

Hope and fear are useless. Be confident, and always be prepared for the worst.
  首页  :: 新随笔  :: 联系 :: 管理

WPF : 如何使用DataTemplateSelector

Posted on 2009-09-21 22:21  mrfangzheng  阅读(982)  评论(0编辑  收藏  举报

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>