如何在MVVM Light WPF C#中动态更改TreeViewItem选择上的UserControl(在View中不对TreeView Selection事件进行硬编码)

How to dynamically change UserControl on TreeViewItem Selection in MVVM Light WPF C# (Without hard coding TreeView Selection event in View )

我正在使用MVVM Light,我有一个简单的问题。我想在TreeViewItem Selection上动态更改UserControl(由MainWindow上的Content Control托管)。

完工

我在MainViewModel中创建了一个属性,用于跟踪当前选定的ViewModel。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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");
      }
   }
}

我还在相应ViewModel的Windows.Resource中创建了一个DataTemplate来更改Selection上的UserControl

1
2
3
4
5
6
7
<wyn><DataTemplate DataType="{x:Type ViewModel1}">
            <Tu:View1/>
        </DataTemplate>
        <DataTemplate DataType="{x:Type ViewModel2}">
            <Tu:View2 />
        </DataTemplate>
</wyn>

现在,唯一需要关注的是我应该如何在树形视图中对CurrentViewModel属性进行数据绑定,以便内容控件中的Usercontrol发生更改??

编辑

Windows中的

HDT.resource

1
2
3
4
5
[cc lang="csharp"] <HierarchicalDataTemplate ItemsSource="{Binding list}" DataType="{x:Type th:Tu}">
        <StackPanel Orientation="Horizontal">
            <Label Content="{Binding list}"/>
        </StackPanel>
    </HierarchicalDataTemplate>

1
[cc lang="csharp"]<TreeView Name="Tree" Background="#FF808080" Margin="0" ItemsSource="{Binding Tubelist}" />

树视图绑定到一个名称列表。这些名称对应于UserControl,我要的是在选择树视图中的该名称时,应选择相应的usercontrol。


如果数据绑定为TreeView,则只需将ContentControl.Content绑定到其SelectedItem

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

因此,您甚至不需要CurrentViewModel属性。