WPF用户控件与父视图/视图模型的交互
我有一个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}" />
到目前为止,一切都很好。在更改datetime属性时,我创建一个列表,该列表然后绑定到mainview上其他位置的数据网格。
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.
我的问题是与要添加到主视图的用户控件有关。我希望此usercontrol是自包含的,因此已经使用其自己的viewmodel创建了它,但它确实还需要访问 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
我认为最好的方法是在usercontrol上创建dependencyProperty,然后在主视图中创建控件时,将dp绑定到datetime,如下所示。
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}" />
问题是如何让用户控件使用其viewmodel维护数据上下文,但仍然具有依赖项属性绑定
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.
非常感谢您提供任何建议。
Thanks very much for any advice.
尝试
<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} />