9

假设以下 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。如何同时指定 aDataTemplateSelectorHeaderTemplate

4

1 回答 1

8

我认为您要做的是设置单个 GridViewColumn 及其标题的样式。所以将 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>
于 2012-04-04T11:55:42.593 回答