将属性与父 ViewModel 绑定 [英] Binding property with parent ViewModel

查看:34
本文介绍了将属性与父 ViewModel 绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参考如何告诉我的 DataTemplate 绑定到 PARENT ViewModel 中的属性?

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

I have similar problem... But this solution didn't work for me. I have a MainViewModel which has an observable collection of another view model say View1/ViewModel1. This view has a tree control and I need context menu for the tree. My main view has a menu. Those main menu and context menu are connected. So how can I bind the context menu commands to the main viewmodel's properties?

推荐答案

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

Basically, you need to use a RelativeSource binding. The standard way is to find an ancestor (or parent) of the control of a particular type:

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

假设你的父视图有一个视图模型设置为它的 DataContext,这个绑定将访问它......DataContextDataContext> 视图,例如.设置为 DataContext 的视图模型.因此,PropertyName 属性是该视图模型的公共属性.

Assuming that your parent view has a view model set to its DataContext, this binding will access it... the DataContext is the DataContext of the view, eg. the view model that is set as the DataContext. So, the PropertyName property is a public property from that view model.

关于您之前被问过很多次的问题,请查看以下链接(或仅在线搜索):

Regarding the part of your question that has been asked so many times before, please see the following links (or just search online):

WPF 中的上下文菜单

将 ContextMenu 绑定到它的逻辑父

这篇关于将属性与父 ViewModel 绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆