如果我在MainWindow视图上有2个UserControl,并且我想在它们之间传递属性,我该怎么做?

时间:2013-12-13 16:37:06

标签: c# wpf xaml mvvm user-controls

我有两个UserControl,1只包含一个TreeView,另一个是在选择TreeView中的项目时加载的表单。

喜欢这个选项对话框。

Options Dialog

我已经遇到过TreeView的SelectedItem属性的几个问题,但是已经找到了几个解决方案来在TreeView的代码隐藏文件或ViewModel中获取SelectedItem。

我的问题是: 如何将TreeView的SelectedItem从它所属的UserControl传递到同一窗口中的ContentControl?

这是我的意思的一个例子:

<Window x:Class="Project.MainWindow"
        xmlns:v="clr-namespace:MicroMVVM.View">
    <v:TreeViewControl /> <!-- Pass SelectedItem from here -->
    <ContentControl Content="TreeViewsSelectedItem" /> <!-- To here. -->
</Window>

1 个答案:

答案 0 :(得分:1)

将正确类型的属性添加到您设置为Window.DataContext的任何对象中,然后从两个子视图中绑定到该值:

<Window x:Class="Project.MainWindow"
        xmlns:v="clr-namespace:MicroMVVM.View">
    <v:TreeViewControl SelectedItem="{Binding SelectedItem}" />
    <ContentControl Content="{Binding SelectedItem}" />
</Window>

您甚至可以直接绑定:

<Window x:Class="Project.MainWindow"
        xmlns:v="clr-namespace:MicroMVVM.View">
    <v:TreeViewControl Name="TreeViewControl" />
    <ContentControl Content="{Binding SelectedItem, ElementName=TreeViewControl}" />
</Window>