[英]How to dynamically change UserControl on TreeViewItem Selection in MVVM Light WPF C# (Without hard coding TreeView Selection event in View )
I am working with MVVM Light and I have a simple question. 我正在使用MVVM Light,我有一个简单的问题。 I want to dynamically change the UserControl (Hosted by Content Control On the MainWindow) on TreeViewItem Selection.
我想在TreeViewItem Selection上动态更改UserControl(由MainWindow上的Content Control托管)。
I created a property in the MainViewModel that keep tracks of the current selected ViewModel. 我在MainViewModel中创建了一个属性,用于跟踪当前选定的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 我还在相应ViewModel的Windows.Resource中创建了一个DataTemplate来更改选择时的UserControl
<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??? 现在,唯一需要关注的是我应该如何在Treeview中对CurrentViewModel属性进行数据绑定,以便更改内容控件中的Usercontrol?
HDT in Windows.resource Windows.resource中的HDT
<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. 树视图绑定到一个名称列表。这些名称对应于UserControl,我要的是在选择树视图中的名称时应选择相应的usercontrol。
If you have data bound TreeView
, you can just bind ContentControl.Content
to its SelectedItem
: 如果您有绑定
TreeView
数据,则可以将ContentControl.Content
绑定到其SelectedItem
:
<ContentControl Content="{Binding SelectedItem, ElementName=myTreeView}"/>
Thus, you even don't need CurrentViewModel
property. 因此,您甚至不需要
CurrentViewModel
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.