假设以下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。 如何同时指定DataTemplateSelector
和HeaderTemplate
?
答案 0 :(得分:7)
我认为你要做的是设计一个GridViewColumn及其Header。 因此,将TemplateSelector从ListView移动到GridViewColumn定义:
<Grid>
<ListView ItemsSource="{Binding Source={StaticResource XmlData}, XPath='/Items/Item'}">
<ListView.View>
<GridView>
<GridViewColumn Width="Auto" CellTemplateSelector="{StaticResource TypeSelector}" HeaderTemplate="{StaticResource HeaderTemplate}"/>
</GridView>
</ListView.View>
</ListView>
</Grid>