问题描述
我有一个TreeView
绑定到Tileset
的列表. Tileset
包含TileGroup
,TileGroup
包含Tile
和TileRun
实例. Tile
和TileRun
都实现ITile
,但是最终将有更多类型实现ITile
I have a TreeView
bound to a list of Tileset
. Tileset
contains TileGroup
, TileGroup
contains both Tile
and TileRun
instances. Both Tile
and TileRun
implement ITile
, but eventually there will be many more types implementing 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>
Tileset
和TileGroup
选择正确的DataTemplate
,但ITile
没有,没有选择模板,树仅显示数据类型.
Tileset
and TileGroup
choose the correct DataTemplate
but ITile
does not, no template is selected, the tree just displays the data type.
但是,如果我同时为Tile
和TileRun
添加一个DataTemplate
,那么一切都很好,但是我不想这样做,因为最终会有更多的类实现ITile
.
However, if I add a DataTemplate
for both Tile
and TileRun
explicitly, everything works great.I don't want to do that though, as there will eventually be many more classes implementing ITile
.
我知道我可以使用DataTemplateSelector
来处理此问题,但如果可能的话,我希望使用纯XAML解决方案.
I am aware that I could handle this using a DataTemplateSelector
, but I'd like a pure XAML solution if possible.
我在这里做错什么了吗,还是WPF只是不支持这种基于接口的自动模板选择类型?
Am I doing something wrong here, or does WPF just not support this type of automatic template selection based on interfaces?
推荐答案
您没有做错任何事情.完全不支持这种对接口的数据绑定支持.有关原因的更多信息,请参考MSDN论坛上以下主题中的Beatriz Costa(MSFT)答案.
You are not doing something wrong. This kind of data binding support for interfaces is simply not supported. Please refer to Beatriz Costa's (MSFT) answer in the following thread on the MSDN forums for more information about why.
"数据绑定小组不久前讨论了添加对接口的支持,但最终由于没有为它设计出好的设计而未能实现.问题是接口没有像这样的层次结构考虑一下您的数据源同时实现IMyInterface1和IMyInterface2并在资源中为这两个接口都具有DataTemplates的情况:您认为我们应该选择哪种DataTemplate?
在对对象类型进行隐式数据模板化时,我们首先尝试查找确切类型的DataTemplate,然后为其父,祖父母等查找数据模板.有非常明确的类型顺序供我们应用.当我们谈论增加对接口的支持时,我们考虑使用反射来找出所有接口并将它们添加到类型列表的末尾.我们遇到的问题是在类型实现多个接口时定义接口的顺序."
因此,您将必须为Tile和TileRun明确定义一个DataTemplate或使用DataTemplateSelector.
So you will either have to define a DataTemplate for both Tile and TileRun explicitly or use a DataTemplateSelector.
这篇关于WPF中的自动模板选择不适用于界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!