3
votes

I have a usercontrol which contains a TreeView control. I am using MVVM pattern. I want to reuse this user control in different windows, each time binding the usercontrol to a different datacontext.

   <UserControl Name="UserControl1".......>

      ..............

        <TreeView ItemSource={Binding ...}...>


             <HierarchicalDataTemplate...........\>

        </TreeView>

      .............. 

   </UserControl>

In window 1, I want to bind a List<ObjectA> to the TreeView.

In Window 2, I want to bind a List<ObjectB> to the TreeView.

Is it possible to write a generic ViewModel for this usercontrol, so that I can bind different Types of data to the TreeView?? In case my question is not understood, please do let me know.

1

1 Answers

2
votes

If I am reading this correctly, you have a UserControl which you wish to reuse, setting its DataContext to be different ViewModel's in different parts of your application...

that being so, yes you can certainly specify Lists of different types as an ItemsSource for your TreeView, but:

  • The list property must be consistently named within each ViewModel
  • You will need to describe a DataTemplate (or HierarchicalDataTemplate) for each type you expect to pass into the TreeView within your control's xaml
  • You may find that binding to an ObservableCollection<T> brings greater reward than a List<T> if you wish to add/remove items to/from the collection and hope to see those changes reflected in the UI

Hope this helps :)