3

Problem

I've got a collection of IThings and I'd like to create a HierarchicalDataTemplate for a TreeView. The straightforward DataType={x:Type local:IThing} of course doesn't work, probably because the WPF creators didn't want to handle the possible ambiguities.

Since this should handle IThings from different sources at the same time, referencing the implementing class is out of question.

Current solution

For now I'm using a ViewModel which proxies IThing through a concrete 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 (i.e. no proxy) way?

David Schmitt
  • 58,259
  • 26
  • 121
  • 165

3 Answers3

5

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>
Daniel Rose
  • 17,233
  • 9
  • 65
  • 88
3

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.

  • I guess you mean http://msdn.microsoft.com/en-us/library/system.windows.controls.datatemplateselector.aspx ? That's probably a good idea! – David Schmitt Dec 16 '08 at 18:39
  • @Richard: It doesn't necessarily have to be a *concrete type*. Even abstract types work fine. I had a similar problem and I replaced the IThing interface by AbstractThing abstract class. – chikak Dec 12 '10 at 14:06
2

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.