0
votes

I'm currently developing a WPF application using the MVVM pattern. The View, Model, ViewModel each are in a seperate Class Library.

My View has a TreeView control which should be filled using databinding.

I get my data from a WCF service which is accessed through the Model. My Model has a service references to the WCF service and calls a method from the WCF to retrieve a nested collection.

The ViewModel makes the data available to the View. Retrieving the data etc all works fine, except for showing it in the TreeView.

My XAML for the TreeView looks like this

<TreeView Grid.Row="1" ItemsSource="{Binding CustomerTree}" >
            <TreeView.Resources>
                <HierarchicalDataTemplate DataType="{x:Type ....}" ItemsSource="{Binding Path=Children}">
                    <TextBlock Text="{Binding Path=Name}"/>
                </HierarchicalDataTemplate>
                <HierarchicalDataTemplate DataType="{x:Type ....}" ItemsSource="{Binding Path=Children}">
                    <TextBlock Text="{Binding Path=ID}"/>
                </HierarchicalDataTemplate>
            </TreeView.Resources>
        </TreeView>

The DataType="{x:Type .....} property expects a certain Type which should be one of the types in my nested collection, but the view does not know which types are available. My ViewModel can access the types the service reference has in the model, for example the customer type by using Model.ServiceReference.Customer.

Is the Model the right place to add a service reference? How should I make my TreeView display the data?

Thanks,

Grant

1

1 Answers

0
votes

You will have to inconvenience yourself a bit to get at the desired level of abstraction. The solution to this issue requires a number of steps:

  1. Don't define a DataType for your templates (use x:Key instead). This is the source of the inconvenience: the templates won't be applied automatically anymore. But on the plus side, you just got rid of references to specific type names.
  2. Use the ItemTemplate or ItemTemplateSelector property on the TreeView to manually select the HierarchicalDataTemplate for each item.

For the second step, descriptions and examples for both techniques are provided by my answer to another question.

The end result is that you will be able to select the desired template without needing to reference specific types in XAML but by utilizing a property on the databound object instead.