假设以下 XAML 定义的窗口:
<Window x:Class="LayoutTests.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:LayoutTests"
Title="Window1">
<Window.Resources>
<XmlDataProvider x:Key="XmlData" IsInitialLoadEnabled="True">
<x:XData>
<Items xmlns="">
<Item text="Item 1" type="A" />
<Item text="Item 2" type="B" />
<Item text="Item 3" type="A" />
</Items>
</x:XData>
</XmlDataProvider>
<DataTemplate x:Key="TypeATemplate">
<TextBlock Text="{Binding XPath=./@text}" Foreground="Red"/>
</DataTemplate>
<DataTemplate x:Key="TypeBTemplate">
<TextBlock Text="{Binding XPath=./@text}" Foreground="Green"/>
</DataTemplate>
<DataTemplate x:Key="HeaderTemplate">
<TextBlock Text="A Header"/>
</DataTemplate>
<local:TypeSelector x:Key="TypeSelector" TypeATemplate="{StaticResource TypeATemplate}" TypeBTemplate="{StaticResource TypeBTemplate}"/>
</Window.Resources>
<Grid>
<ListView ItemsSource="{Binding Source={StaticResource XmlData}, XPath='/Items/Item'}" ItemTemplateSelector="{StaticResource TypeSelector}">
<!--<ListView.View>
<GridView>
<GridViewColumn Width="Auto" HeaderTemplate="{StaticResource HeaderTemplate}"/>
</GridView>
</ListView.View>-->
</ListView>
</Grid>
</Window>
并DataTemplateSelector
在后面的代码中定义如下:
public class TypeSelector : DataTemplateSelector
{
public DataTemplate TypeATemplate { get; set; }
public DataTemplate TypeBTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
var element = item as XmlElement;
if (element.Attributes["type"].Value == "A")
return TypeATemplate;
else
return TypeBTemplate;
}
}
如果没有注释掉标头模板的代码,则不再调用 DataTypeSelector。如何同时指定 aDataTemplateSelector
和HeaderTemplate
?