首页 > 代码库 > 如何使用ItemTemplateSelector

如何使用ItemTemplateSelector

WPF 的 ItemsControl 数据绑定中,有时会遇到绑定的数据源是多种类型,并且需要对不同类型使用不同的模板。这个时候就需要用到 ItemTemplateSelector。

 

ItemTemplateSelector 的定义

ItemTemplateSelector 是 DataTemplateSelector 类型,通常需要定义一个类继承 DataTemplateSelector。

注意,下面代码关键之处在于定义了 DataTemplate 类型的属性,并在 XAML 中设置其值,避免寻找资源。

public class ValueEditorTemplateSelector : DataTemplateSelector{	public DataTemplate StandardTemplate	{		get { return this.standardTemplate; }		set { this.standardTemplate = value; }	}	public DataTemplate EnumTemplate	{		get { return this.enumTemplate; }		set { this.enumTemplate = value; }	}	public override DataTemplate SelectTemplate(object item, DependencyObject container)	{		PropertyInformation property = (PropertyInformation)item;		if (property.PropertyType.IsEnum)			return EnumTemplate;		return StandardTemplate;	}}

ItemTemplateSelector 的使用

<my:ValueEditorTemplateSelector x:Key="EditorSelector">    <my:ValueEditorTemplateSelector.StandardTemplate>        <DataTemplate>            <DockPanel>                <editors:MouseWheelValueEditor/>                <my:StandardValueEditor                    PropertyType="{Binding PropertyType}"                    Value="{Binding Value, Mode=TwoWay}"                    DescriptiveValue="{Binding DescriptiveValue, Mode=OneWay}"                    IsSelected="{Binding IsSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListViewItem}}}"                    IsEditable="{Binding CanEdit}"                    PropertyInfo="{Binding}"/>                <Border/>            </DockPanel>        </DataTemplate>    </my:ValueEditorTemplateSelector.StandardTemplate>    <my:ValueEditorTemplateSelector.EnumTemplate>        <DataTemplate>            <DockPanel>                <editors:MouseWheelValueEditor/>                <my:EnumValueEditor                    PropertyType="{Binding PropertyType}"                    Value="{Binding Value, Mode=TwoWay}"                    DescriptiveValue="{Binding DescriptiveValue, Mode=OneWay}"                    IsSelected="{Binding IsSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListViewItem}}}"                    IsEditable="{Binding CanEdit}"                    PropertyInfo="{Binding}"/>                <Border/>            </DockPanel>        </DataTemplate>    </my:ValueEditorTemplateSelector.EnumTemplate></my:ValueEditorTemplateSelector>

 

如何使用ItemTemplateSelector