【问题标题】:Automatic template selection in WPF not working with interfaceWPF中的自动模板选择不适用于界面
【发布时间】:2016-12-30 01:22:43
【问题描述】:

我有一个TreeView 绑定到Tileset 的列表。 Tileset 包含 TileGroupTileGroup 包含 TileTileRun 实例。 TileTileRun 都实现了ITile,但最终会有更多的类型实现ITile

我有以下 XAML:

<TreeView
    Grid.Row="0"
    Grid.Column="0"
    BorderThickness="0"
    ItemsSource="{Binding Path=Tilesets}">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type local:Tileset}" ItemsSource="{Binding Path=TileGroups}">
            <TextBlock Text="{Binding Path=Name}" />
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate DataType="{x:Type local:TileGroup}" ItemsSource="{Binding Path=Tiles}">
            <TextBlock Text="{Binding Path=Name}" />
        </HierarchicalDataTemplate>
        <DataTemplate DataType="{x:Type tiles:ITile}">
            <TextBlock Text="{Binding Path=Name}" />
        </DataTemplate>
    </TreeView.Resources>
</TreeView>

TilesetTileGroup 选择正确的DataTemplateITile 没有选择,没有选择模板,树只显示数据类型。

但是,如果我明确地为TileTileRun 添加DataTemplate,一切都会很好。不过我不想这样做,因为最终会有更多的类实现ITile

我知道我可以使用 DataTemplateSelector 来处理这个问题,但如果可能的话,我想要一个纯 XAML 解决方案。

我在这里做错了什么,还是 WPF 只是不支持这种基于接口的自动模板选择?

【问题讨论】:

标签: wpf xaml mvvm


【解决方案1】:

我在这里做错了什么,还是 WPF 不支持这种基于接口的自动模板选择?

你没有做错什么。根本不支持这种对接口的数据绑定支持。有关原因的更多信息,请参阅 MSDN 论坛上以下主题中 Beatriz Costa (MSFT) 的回答。

数据模板和接口: https://social.msdn.microsoft.com/Forums/vstudio/en-US/1e774a24-0deb-4acd-a719-32abd847041d/data-templates-and-interfaces?forum=wpf

“数据绑定团队不久前讨论过添加对接口的支持,但最终没有实现它,因为我们无法为它提出一个好的设计。问题是接口没有像这样的层次结构对象类型可以。考虑一下您的数据源同时实现 IMyInterface1 和 IMyInterface2 并且您在资源中为这两个接口都有 DataTemplates 的场景:您认为我们应该选择哪个 DataTemplate?

在为对象类型做隐式数据模板时,我们首先尝试为确切的类型找到一个 DataTemplate,然后为它的父、祖父等找到一个 DataTemplate。有非常明确的类型顺序供我们应用。当我们谈到添加对接口的支持时,我们考虑使用反射来找出所有接口并将它们添加到类型列表的末尾。我们遇到的问题是在类型实现多个接口时定义接口的顺序。”

因此,您要么必须为 Tile 和 TileRun 显式定义 DataTemplate,要么使用 DataTemplateSelector。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多