WPF Usercontrol interaction with parent view / viewmodel
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 开发者_JAVA百科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.
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} />
精彩评论