WPF HiercharchicalDataTemplate.DataType: how to respond to interfaces?

Problem

I have a collection IThingand I would like to create HierarchicalDataTemplatefor TreeView. Simple DataType={x:Type local:IThing}, of course, does not work, perhaps because the creators of WPF did not want to handle possible ambiguities.

Since this should process IThingfrom different sources at the same time, a reference to the implementation class is out of the question.

Current solution

I am currently using ViewModel, which proxies IThing through a specific implementation:

public interface IThing {
    string SomeString { get; }
    ObservableCollection<IThing> SomeThings { get; }
    // many more stuff
}

public class IThingViewModel
{
     public IThing Thing { get; }
     public IThingViewModel(IThing it) { this.Thing = it; }
}

<!-- is never applied -->
<HierarchicalDataTemplate DataType="{x:Type local:IThing}">

<!-- is applied, but looks strange -->
<HierarchicalDataTemplate
    DataType="{x:Type local:IThingViewModel}"
    ItemsSource="{Binding Thing.SomeThings}">
    <TextBox Text="{Binding Thing.SomeString}"/>
</HierarchicalDataTemplate>

Question

Is there a better way (i.e. without a proxy)?

+3
source share
3 answers

, , . DataTemplateSelector ItemTemplateSelector TreeView. URL-, , , , , Google.

+3

( ): , ItemTemplate. .

ViewModel:

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

:

<TreeView ItemsSource="{Binding Thingies}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding SomeThings}">
            <TextBox Text="{Binding SomeString}" />    
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>
+4

- HierarchicalDataTemplate Windows.Resources TreeView. <TreeView ItemDataTemplate={StaticResource templateKey}/>

, WPF TreeView.

+2
source

Source: https://habr.com/ru/post/1699065/


All Articles