0
votes

I'm getting myself all in a pickle with TreeViews and User Controls; I'm fairly new to WPF so apologies in advance.

Synopsis

I have a collection of VM classes for my TreeView Items. So the TreeView is bound to a collection of [Parent] VM instances, each of which has a collection of [Child]ren, and each [Child] has other data and other collections (which I won't bore you with).

The TreeView is on the left side of the form, and on the right I have a user control which should only be visible depending on the selected TreeViewItem type.

So, if the selected item of the TreeView is of '[Child]' type then the User Control should be visible.

Problem

I'm struggling with how to detect when an Item in the TreeView is selected so that I can show/hide the User control.

One way I thought of, but do not like, is to bind the 'IsSelected' property of the TreeViewItem to the [Child] VM class, then raise an event up to the main VM, which would show/hide the UC via DP's. But this requires a whole load of Events etc and to me, just seems, messy.

Summary

For the life of me I cannot work out how to do this, I must be tired or something...or stupid...or both.

All I want to do is select an Item on the TreeView and the appropriate UserControl displays with the relevant data of the TreeViewItem, which I could in Windows Forms very easily, but obviously I'm not thinking about this in a very WPF'ish way at the moment.

Any links to articles etc appreciated.

Big up your chest for any responses.

1

1 Answers

2
votes

In your case, i would prefer a DataTemplateSelector. It´s a object which provides a way to select a DataTemplate based on the databound object - here your ViewModel.

Just put a ContentControl in your Window and bind the Content-Property to the SelectedItem-Property of your TreeView. Set the ContentTemplateSelector-Property of the ContentControl to a reference of your own DataTemplate Selector.

The DataTemplateSelector will choose the correct DataTemplate with the defined UserControl by your requirements.

   <DataTemplate x:key="VMParent">
      <local:ParentUI DataContext="{Binding}" />
   </DataTemplate/>

   <DataTemplate x:key="VMChild">
      <local:ChildUI DataContext="{Binding}" />
   </DataTemplate/>

Greetings :)