WPF HiercharchicalDataTemplate.DataType: How to react on interfaces?

后端 未结 3 429
有刺的猬
有刺的猬 2021-01-14 18:44

Problem

I\'ve got a collection of IThings and I\'d like to create a HierarchicalDataTemplate for a TreeView. The straightfor

相关标签:
3条回答
  • 2021-01-14 19:16

    The reason for this is that the default template selector supports only concrete types, not interfaces. You need to create a custom DataTemplateSelector and apply it to the ItemTemplateSelector property of the TreeView. I can't find the URL where I found an example of it, but hopefully with this info, you can Google it.

    0 讨论(0)
  • 2021-01-14 19:26

    Another solution is you give a key to the HierarchicalDataTemplate and put it in the Windows.Resources, and manually reference to it in the TreeView. <TreeView ItemDataTemplate={StaticResource templateKey}/>

    But that limits the autoselection of data template according to data type, which is provided by WPF TreeView.

    0 讨论(0)
  • 2021-01-14 19:27

    Another alternative (similar to jing's solution): If you only have one type of item, you can set the ItemTemplate directly. Then you don't need to set a key or a datatype.

    In your ViewModel:

    public ObservableCollection<IThing> Thingies { get; private set; }
    

    In the View:

    <TreeView ItemsSource="{Binding Thingies}">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding SomeThings}">
                <TextBox Text="{Binding SomeString}" />    
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
    
    0 讨论(0)
提交回复
热议问题