wpf - 与父 ViewModel 绑定(bind)属性

标签 wpf viewmodel

请引用How can I tell my DataTemplate to bind to a property in the PARENT ViewModel?

我有类似的问题......但这个解决方案对我不起作用。我有一个 MainViewModel,它有另一个 View 模型的可观察集合,比如 View1/ViewModel1。这个 View 有一个树控件,我需要树的上下文菜单。我的主视图有一个菜单。那些主菜单和上下文菜单是相连的。那么如何将上下文菜单命令绑定(bind)到主视图模型的属性呢?

最佳答案

基本上,您需要使用 RelativeSource捆绑。标准方法是查找特定类型控件的祖先(或父级):

{Binding DataContext.PropertyName, RelativeSource={RelativeSource FindAncestor, 
    AncestorType={x:Type YourViewsNamespace:YourParentView}}}

假设您的父 View 有一个 View 模型设置为其 DataContext ,此绑定(bind)将访问它... DataContextDataContext的观点,例如。设置为 DataContext 的 View 模型.所以,PropertyName property 是该 View 模型的公共(public)属性。

关于你之前被问过很多次的部分问题,请看以下链接(或直接在网上搜索):

Context Menus in WPF

Binding ContextMenu to its logical Parent

关于wpf - 与父 ViewModel 绑定(bind)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18717241/

相关文章:

c# - 如何在MVVM Xamarin Forms中将参数传递给Singleton

c# - Entity Framework 模型与 ViewModel 的最佳实践

c# - 无法转换为基类

c# - WPF 绑定(bind) ItemsControl 中的字符串值列表

c# - 如何在我的 ViewModel 中监听来自另一个 ViewModel 的更改?

android - 在文件 '/activity_login.xml' DataBinding 中发现重复的类,未生成 BR

c# - 在此示例 MVVM 应用程序中使用模型是否有意义?

c# - WinForms 到 WPF 的迁移

wpf - 我可以将 HTML 绑定(bind)到 WPF Web 浏览器控件吗?

c# - 从 ViewModel 打开/关闭 View