Search code examples
wpfdata-bindingmvvmtreeviewrouted-events

What's the preferred method of reacting to a selected item change using the TreeView?


What's the preferred method of updating other controls when a TreeViewItem has been selected?

Currently I have the following structure in my TreeView

DataStoreType - (DataStoreTypeViewModel)
    DataStoreEntry - (DataStoreEntryViewModel)
    DataStoreEntry - (DataStoreEntryViewModel)
    DataStoreEntry - (DataStoreEntryViewModel)
DataStoreType - (DataStoreTypeViewModel)
    DataStoreEntry - (DataStoreEntryViewModel)
    DataStoreEntry - (DataStoreEntryViewModel)
    DataStoreEntry - (DataStoreEntryViewModel)

It's using the MVVM pattern, with each of the two treeview item types populated by a specific View-Model (the DataStoreTypeViewModel and DataStoreEntryViewModel).

When the user selects one of the nodes (either a DataStoreType or a DataStoreEntry) I need to be able to populate a list control with information based on the selection. So the list control needs to be able to display two different sets of data.

I've read a little about RoutedEvents, but not sure if that's the way to go...

Thanks
Kieron


Solution

  • If you take the approach taken here then you can set a property on the view model of the selected item. Depending on the relationship between DataStoreType and DataStoreEntry you can use the same property on the view model either storing the base class or interface.

    Within the property you can react by setting a collection that your list control is bound to...

    VM

    public IDataStore SelectedStore
    {
        get { return _store; }
        set 
        {
            _store = value;
            RaisePropertyChanged("SelectedStore");
            RaisePropertyChanged("ListItems");
        }
     }
    
     public IEnumerbale<string> ListItems
     {
         get 
         { 
              if(_store == null)
                   return Enumerable.Empty<string>();
              else 
                   return _store.Items; 
         }
     } 
    

    XAML

    <ListBox ItemsSource="{Binding ListItems}" />
    

    Because of the RaisePropertyChanged("ListItems"); in the setter for the selected item in the tree view the ListBox (assuming you are using something like that) will update with the new data. In this design I am retrieving the list of items from either the DataStoreTypeViewModel or DataStoreEntryViewModel which is better encapsulation if the data varies based on the view model type. Just have them implement an interface like IDataStore.

    Just tweak it to suit your needs.