惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

M
MIT News - Artificial intelligence
AI
AI
月光博客
月光博客
爱范儿
爱范儿
博客园 - 司徒正美
Last Week in AI
Last Week in AI
博客园 - 三生石上(FineUI控件)
S
Security @ Cisco Blogs
腾讯CDC
W
WeLiveSecurity
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Help Net Security
Help Net Security
人人都是产品经理
人人都是产品经理
WordPress大学
WordPress大学
Cyberwarzone
Cyberwarzone
K
Kaspersky official blog
Security Latest
Security Latest
博客园 - 叶小钗
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
A
Arctic Wolf
C
Cisco Blogs
H
Heimdal Security Blog
雷峰网
雷峰网
阮一峰的网络日志
阮一峰的网络日志
Google DeepMind News
Google DeepMind News
小众软件
小众软件
T
Tenable Blog
Attack and Defense Labs
Attack and Defense Labs
N
News and Events Feed by Topic
The Last Watchdog
The Last Watchdog
V2EX - 技术
V2EX - 技术
Simon Willison's Weblog
Simon Willison's Weblog
Vercel News
Vercel News
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
V
Vulnerabilities – Threatpost
L
LangChain Blog
Y
Y Combinator Blog
V
V2EX
Hacker News - Newest:
Hacker News - Newest: "LLM"
Latest news
Latest news
D
Docker
AWS News Blog
AWS News Blog
Google Online Security Blog
Google Online Security Blog
H
Help Net Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Troy Hunt's Blog
TaoSecurity Blog
TaoSecurity Blog
Cloudbric
Cloudbric
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC

博客园 - umlchina

.Net桌面程序自动更新NAppUpdate c# interview examination questions how to use wpf control in a winform application prism框架里module太多启动速度过慢 Localizing of WPF application Unity 中的拦截功能 Interception and Interceptors in C# (Aspect oriented programming) 转载 WPF Snippet Tutorial - Aligning ListView Items Dependency Properties Introduction To Dependency Properties of WPF 朋友的公司招.net程序员2名及项目经理1名 Simple Object Access Protocol (SOAP) 1.1 how to create pdf by itextsharp convert RGB colorspace to Homochromy(Black/whit) - umlchina 图片处理转换 how to design a hardware service use .net remoting : 使用SAAJ发送和接收SOAP消息 consume an asp.net webservice(upload a file to server) from java via soap 紧急求助:我们想做一个service程序,这个service负责统一管理这台机器上装的一些设备(包括签字板,扫描仪等等),
WPF Tutorial - How To Use A DataTemplateSelector
umlchina · 2010-08-26 · via 博客园 - umlchina

DataTemplates are an extremely powerful part of WPF, and by using them, you can abstract all sorts of display code. However, there are times when they fall short - and initially when I was learning WPF I was disappointed by that. For instance, you only get to set one DataTemplate on an items control, and while that made sense, it felt limiting. What if I wanted to use different templates depending on the content of the item? Do I have to build all that logic into a single data template?

And then I discovered DataTemplateSelectors! They are WPF's answer to the question I posed above - they let you write some logic that chooses what data template to use for an item. You could even, say, create an entirely new data template on the fly if you needed to. And it helps with one of WPF's main goals, separating out display (the DataTemplate itself) from logic (the DataTemplateSelector).

We are going to write a simple little application today, that is essentially just a list view containing a collection of strings. However, there is a twist - if the string is a path to an image on disk, instead of displaying the string, the list view will display the image. You can see a screenshot of it in action below:

App Screenshot

Time to dive into some code. First, lets write the two DataTemplates we need - one displaying the image, and one for displaying the string:

<DataTemplate x:Key="stringTemplate">
<TextBlock Text="{Binding}"/>
</DataTemplate>
<DataTemplate x:Key="imageTemplate">
<Image Source="{Binding Converter={StaticResource relToAbsPathConverter}}"
Stretch="UniformToFill" Width="200"/>
</DataTemplate>

Simple enough stuff. For when we just want to display the string, we use a TextBlock and bind the Text to the current item. When that string is an image path, however, we will be using an Image and binding the Source property to the string. The only quirk here is how the source property gets interpreted. If the path is relative, the Source property will think it is a reference to an internal program resource, and not a file on disk. So we have a converter that takes the relative path string and converts it to an absolute path string. You can learn more about binding converters here, in a tutorial that The Reddest wrote just the other day.

Since I was just talking about the converter, might as well get the code for it out of the way:

public class RelativeToAbsolutePathConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
String relative = value as string;
if (relative == null)
return null;
return System.IO.Path.GetFullPath(relative);
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}

All we do is cast the value to a string, and then use the handy GetFullPath method to get the full path for the given relative path. Since we don't need to use the ConvertBack method, I just have it set to throw a NotImplementedException.

Now that we have our Data Templates, lets write the DataTemplateSelector:

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;
}
}

As you can see, to make your own DataTemplateSelector you create a class that extends the class DataTemplateSelector. This class has a single method that we need to override - SelectTemplate. This method will get called and get passed an item, and it needs to return what DataTemplate to use for that item. Here, we expect the item to be a string - and if the string represents a file path, and the file exists, and the extension is ".jpg", we return the template we are using for images, otherwise we return the template we are using for strings.

You are probably wondering, however, where the properties ImageTemplate and StringTemplate actually get set to the Data Templates we created earlier. Well, this happens in the xaml when we create an instance of the ImgStringTemplateSelector:

<local:ImgStringTemplateSelector
ImageTemplate="{StaticResource imageTemplate}"
StringTemplate="{StaticResource stringTemplate}"
x:Key="imgStringTemplateSelector" />

Ok, now it is time to throw all of the xaml out there so that you can see how the ListView actually uses the ImgStringTemplateSelector we just created:

<Window x:Class="DataTemplateSelectorExample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DataTemplateSelectorExample"
Title="Data Template Selector Example"
Height="300" Width="300" Name="This">
<Window.Resources>
<local:RelativeToAbsolutePathConverter x:Key="relToAbsPathConverter" />
<DataTemplate x:Key="stringTemplate">
<TextBlock Text="{Binding}"/>
</DataTemplate>
<DataTemplate x:Key="imageTemplate">
<Image Source="{Binding Converter={StaticResource relToAbsPathConverter}}"
Stretch="UniformToFill" Width="200"/>
</DataTemplate>
<local:ImgStringTemplateSelector
ImageTemplate="{StaticResource imageTemplate}"
StringTemplate="{StaticResource stringTemplate}"
x:Key="imgStringTemplateSelector" />
</Window.Resources>
<Grid>
<ListView ScrollViewer.CanContentScroll="False"
ItemsSource="{Binding ElementName=This, Path=PathCollection}"
ItemTemplateSelector="{StaticResource imgStringTemplateSelector}">
</ListView>
</Grid>
</Window>

The templates and the selector are all resources in the current window. This makes it so that when we get down to creating the ListView, we can set the ItemTemplateSelector to the static resource imgStringTemplateSelector. We also set the ItemsSource - we bind it to the PathCollection on the element This. What is the element This? Well, it happens to be the name of the window - you can see it up in the Nameproperty of the Window tag. And the PathCollection is a property on Window1:

public partial class Window1 : Window
{
ObservableCollection<string> _PathCollection = new ObservableCollection<string>();
public Window1()
{
    _PathCollection.Add("Sunset.jpg");
    _PathCollection.Add("I'm not an image");
    _PathCollection.Add("Blue hills.jpg");
    _PathCollection.Add("Water lilies.jpg");
    _PathCollection.Add("More string action");
    _PathCollection.Add("Winter.jpg");
    InitializeComponent();
}
public ObservableCollection<string> PathCollection
{ get { return _PathCollection; } }
}

The only other thing of note is the fact that ScrollViewer.CanContentScroll is set to false on the ListView. This is just there to enable smooth scrolling on the list box - it doesn't try and scroll the items one at a time, it lets you scroll partially through an item. It is just a nicety because the ListView will contain images.

Well, that is it for this introduction to the DataTemplateSelector. You can grab the Visual Studio project for what we wrote today here. And, as always, leave any questions or comments below.