wpf 将 UserControl 的数据上下文设置为父视图模型中定义的 ViewModel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13740593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting datacontext of UserControl to ViewModel defined in parent viewmodel
提问by ZymLink
I'm trying to create an application using the MVVM pattern with nested viewmodels. The master viewmodel is ShellView which contains three UserControls, each with their own viewmodel. The ShellView ViewModel is created in code-behind like so:
我正在尝试使用带有嵌套视图模型的 MVVM 模式创建应用程序。主视图模型是 ShellView,它包含三个 UserControl,每个都有自己的视图模型。ShellView ViewModel 是在代码隐藏中创建的,如下所示:
public ShellView()
{
InitializeComponent();
_shellViewModel = new ShellViewModel();
DataContext = _shellViewModel;
}
Now, my ShellViewModel contains the other ViewModels as properties:
现在,我的 ShellViewModel 包含其他 ViewModel 作为属性:
public CustomerViewModel CustomerViewModel { get; set; }
public ContactsViewModel ContactsViewModel { get; set; }
How do I access these properties from the XAML of the UserControls? I would like to be able to do something like:
如何从 UserControls 的 XAML 访问这些属性?我希望能够执行以下操作:
DataContext="<<ParentWindowViewModel>.CustomerViewModel>
How can i accomplish this? I already tried:
我怎样才能做到这一点?我已经尝试过:
DataContext="{Binding DataContext.CustomerViewModel, RelativeSource={RelativeSource FindAncestor, AncestorType=Window, AncestorLevel=1}, Path=DataContext.CustomerViewModel}">
but the debugger says "Cannot resolve property 'CustomerViewModel' in data context of type 'object'. Any help would be appreciated.
但调试器说“无法解析‘对象’类型的数据上下文中的属性‘CustomerViewModel’。任何帮助将不胜感激。
回答by Adi Lester
You simply need to use
你只需要使用
DataContext="{Binding CustomerViewModel}"
You've already set DataContext = _shellViewModel;
in your constructor, so that sets the datacontext of the entire window to ShellViewModel
, so when you define a binding, it looks for the path in the datacontext that you have defined. That's why the above binding will look for the CustomerViewModel
property on your ShellViewModel
instance.
您已经DataContext = _shellViewModel;
在构造函数中进行了设置,因此将整个窗口的数据上下文设置为ShellViewModel
,因此当您定义绑定时,它会在您定义的数据上下文中查找路径。这就是为什么上述绑定会CustomerViewModel
在您的ShellViewModel
实例上查找属性的原因。