wpf 将属性与父 ViewModel 绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18717241/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:37:18  来源:igfitidea点击:

Binding property with parent ViewModel

wpfviewmodel

提问by WpfBegnner

Please refer to How can I tell my DataTemplate to bind to a property in the PARENT ViewModel?

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

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?

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

回答by Sheridan

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

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

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

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

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

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

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

Context Menus in WPF

WPF 中的上下文菜单

Binding ContextMenu to its logical Parent

将 ContextMenu 绑定到其逻辑父级

回答by Sai

1. ParentViewModel has NavigateRecordCommand

2. Parentview has the DataContext Set to my ParentViewModel.

<UserControl x:Class="SampleProject.UI.ParentView"

<Grid>
    ....
<!--User control is here-->
    <local:NavigationControl  Grid.Row="1" />
    ....
</Grid>


3. Child Control as below. Not bounded to its ViewModel. Bounded to Parent Views DataContext i.e. ParentViewModel.

    <UserControl x:Class="SampleProject.UI.NavigationControl"
    ...
    ...
     xmlns:Local="clr-namespace:SampleProject.UI">

    <Button Command="{Binding DataContext.NavigateRecordCommand, RelativeSource={RelativeSource AncestorType=Local:ParentView}}"
            CommandParameter="MoveFirst"/>