1
votes

I am working with MVVM Light and I have a simple question. I want to dynamically change the UserControl (Hosted by Content Control On the MainWindow) on TreeViewItem Selection.


Work Done

I created a property in the MainViewModel that keep tracks of the current selected ViewModel.

private ViewModelBase currentviewmodel;
readonly static ViewModel1 VM1 = new ViewModel1();
readonly static ViewModel2 VM2 = new ViewModel2();

public ViewModelBase CurrentViewModel
{
   get
   {
      return currentviewmodel;
   }
   set
   {
      if (currentviewmodel != value)
      {
         currentviewmodel = value;
         RaisePropertyChanged("CurrentViewModel");
      }
   }
}       

I Have also created a DataTemplate in the Windows.Resource of the respective ViewModel to change the UserControl on Selection

<DataTemplate DataType="{x:Type ViewModel1}" >
            <Tu:View1/>
        </DataTemplate>
        <DataTemplate DataType="{x:Type ViewModel2}" >
            <Tu:View2 />
        </DataTemplate>

Now the only concern is how should i databind the CurrentViewModel property in the treeview so that the Usercontrol in the content control changes???


EDIT

HDT in Windows.resource



 <HierarchicalDataTemplate ItemsSource="{Binding list}" DataType="{x:Type th:Tu}">
        <StackPanel Orientation="Horizontal">
            <Label Content="{Binding list}"/>
        </StackPanel>
    </HierarchicalDataTemplate>



<TreeView Name="Tree" Background="#FF808080" Margin="0" ItemsSource="{Binding Tubelist}" />

The treeview is bound to a list of name.Those name corresponds to the UserControl,what i want is that on selection of that names in the treeview the respective usercontrol should be selected.

1

1 Answers

1
votes

If you have data bound TreeView, you can just bind ContentControl.Content to its SelectedItem:

<ContentControl Content="{Binding SelectedItem, ElementName=myTreeView}"/>

Thus, you even don't need CurrentViewModel property.