WPF 用户控件与父视图/视图模型的交互 [英] WPF Usercontrol interaction with parent view / viewmodel
问题描述
您好,我有一个 mainView 窗口,它的 dataContext 设置为它自己的 viewModel.
Hi I have a mainView window which has its dataContext set to it's own viewModel.
在该 viewModel 上有一个 DateTime 属性,该属性又使用 2 路绑定绑定到我的主视图上的日期选择器.
On that viewModel is a DateTime property which in turn is bound to a datepicker on my main view using 2 way binding.
<toolkit:DatePicker DateSelected="{Binding mainDateTimeProperty, Mode=TwoWay}" />
到目前为止一切都很好.在更改我的日期时间属性时,我创建了一个列表,然后将其绑定到主视图上其他地方的数据网格.这一切都很好.
This is all fine so far. On the change of my datetime property I create a list which is then bound to a datagrid elsewhere on the mainview. This all works fine.
我的问题是关于我想添加到主视图的用户控件.我希望这个用户控件是自包含的,所以用它自己的视图模型创建了它,但它也需要访问 mainDateTimeProperty
My question is to do with a usercontrol I want to add to the main view. I want this usercontrol to be self contained so have created it with it's own viewmodel but it does also need access to mainDateTimeProperty
我认为最好的方法是在用户控件上创建一个 dependencyProperty,当我在主视图中创建我的控件时,我将 dp 绑定到日期时间,如下所示.
I thought that best way to go would be to create a dependencyProperty on the usercontrol and when I create my control in the main view I bind the dp to the datetime as follows.
<uc:MyNewUserControl DateProperty="{Binding mainDateTimeProperty}" />
问题是我如何让用户控件使用它的视图模型维护数据上下文,但仍然将依赖属性绑定到主视图模型上的属性?
Trouble is how do I have the usercontrol maintain datacontext with it's viewmodel and yet still have the dependency property bound to a property on the main view model?
希望这很清楚.如有必要,可以发布更多代码.如果可能,寻找最佳实践方法.
Hope this is clear. Can post some more code if necessary. Looking for a best practice approach if possible.
非常感谢您的建议.
推荐答案
试试
<uc:MyNewUserControl DateProperty="{Binding Parent.DataContext.mainDateTimeProperty, Mode=TwoWay}" />
抱歉,previos 代码不正确.正确的绑定是
Edited: Sorry, previos code was incorrect. Correct binding is
<uc:MyNewUserControl DateProperty="{Binding Path=Parent.DataContext.mainDateTimeProperty, RelativeSource={RelativeSource Self}, Mode=TwoWay} />
这篇关于WPF 用户控件与父视图/视图模型的交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!