WPF Usercontrol interaction with parent view / viewmodel

情到浓时终转凉″ 提交于 2019-12-06 14:01:11

问题


Hi I have a mainView window which has its dataContext set to it's own viewModel.

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.

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

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.

Thanks very much for any advice.


回答1:


Try

<uc:MyNewUserControl DateProperty="{Binding Parent.DataContext.mainDateTimeProperty, Mode=TwoWay}" />

Edited: Sorry, previos code was incorrect. Correct binding is

<uc:MyNewUserControl DateProperty="{Binding Path=Parent.DataContext.mainDateTimeProperty, RelativeSource={RelativeSource Self}, Mode=TwoWay} />


来源:https://stackoverflow.com/questions/3063758/wpf-usercontrol-interaction-with-parent-view-viewmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!