DataTemplateSelector不会被使用

时间:2013-06-01 17:26:53

标签: wpf templates listview datatemplate datatemplateselector

要根据当前的项目类型在我的ItemTemplates中的两个ListView之间切换,我实施了DataTemplateSelector。我通过Binding将其添加到ListView。但是,如果我设置断点,它永远不会被调用。我尝试了一切,没有任何作用。

public class ListViewTemplateSelector : DataTemplateSelector
{
    public DataTemplate SectionTemplate { get; set; }
    public DataTemplate EntryTemplate { get; set; }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        if (item is Section)
        {
            return SectionTemplate;
        }

        if (item is Entry)
        {
            return EntryTemplate;
        }

        return base.SelectTemplate(item, container);
    }
}

XAML:

<ListView DataContext="{Binding ElementName=This}" x:Name="list" Margin="200,25,0,0" ItemsSource="{Binding CurrentSelection}" ItemTemplateSelector="{StaticResource TemplateSelector}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}" Width="100" />
            <GridViewColumn Header="Value" DisplayMemberBinding="{Binding Value}" Width="300" />
        </GridView>
    </ListView.View>
</ListView>

<DataTemplate x:Key="sectionTemplate">
    <StackPanel Orientation="Horizontal">
        <Image Width="16" Height="16" Source="\Icons\blue-folder.png" />
        <TextBlock Text="{Binding ID}" Margin="5,0,0,0" />
    </StackPanel>
</DataTemplate>

<DataTemplate x:Key="entryTemplate">
    <StackPanel Orientation="Horizontal">
        <Image Width="16" Height="16" Source="\Icons\ui-text-field-medium.png" />
        <TextBlock Text="{Binding ID}" Margin="5,0,0,0" />
    </StackPanel>
</DataTemplate>

<sdk:ListViewTemplateSelector x:Key="TemplateSelector" SectionTemplate="{StaticResource sectionTemplate}" EntryTemplate="{StaticResource entryTemplate}" />

有人知道如何解决这个问题吗?

谢谢R

1 个答案:

答案 0 :(得分:2)

来自GridView Overview > GridView Layout and Style&gt;在GridView中定义和设置列:

  

定义要在GridViewColumn中显示的数据字段时,请使用   DisplayMemberBinding,CellTemplate或CellTemplateSelector   属性。 DisplayMemberBinding属性优先于   任何一个模板属性。

因此,您必须从GridViewColumns中删除DisplayMemberBinding并设置CellTemplateSelector而不是ListView的ItemTemplateSelector

<GridView>
    <GridViewColumn Header="ID" Width="100"
                    CellTemplateSelector="{StaticResource TemplateSelector}"/>
    <GridViewColumn Header="Value" Width="300"
                    DisplayMemberBinding="{Binding Value}"/>
</GridView>