该篇文章将介绍WPF中的ItemTemplateSelector的使用,首先,让我们先了解ItemTemplateSelector是什么意思,在什么情况下会使用到此属性。
ItemTemplateSelector:获取或设置选择用于显示每个项的模板的自定义逻辑。(MSDN)
大家都知道ItemTemplate是来指定数据对象的可视化。如果您定义多个模板,并且希望提供逻辑以返回要使用的模板,则可以使用此属性。
本章用ListBox控件对ItemTemplateSelector进行讲解。
步骤:
在下面的示例中,将定义ImgItemTemplateSelector资源名称分配给ListBox的ItemTemplateSelector属性。
其中两个DataTemplate分别为横向布局和纵向布局,然后分别指向两个ControlTemplate。
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Views="clr-namespace:IdeaTouch5Test.Views"
xmlns:Controls1="clr-namespace:IdeaTouch5Test.Controls"
Title="MainWindow"
Height="350"
Width="525">
<Window.Resources>
<ItemsPanelTemplate x:Key="ItemPanleControl">
<VirtualizingStackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
<ControlTemplate x:Key="VerticalContentTemplate"