views:

25

answers:

1

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.

A: 

Try

&lt;uc:MyNewUserControl DateProperty="{Binding Parent.DataContext.mainDateTimeProperty, Mode=TwoWay}" /&gt;

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

<uc:MyNewUserControl DateProperty="{Binding Path=Parent.DataContext.mainDateTimeProperty, RelativeSource={RelativeSource Self}, Mode=TwoWay} />
STO
OK thanks. I'll give that a try. So on another note, would you say that using the dependency property approach and binding like this is the correct way to do things in this kind of parent / child control approach?
obaylis
Why not? If you want to keep your xaml clear of bindings like this, you may expose property of parent view model via child view model if parent view model already have aggregated child view model, and child view model has reference to parent.By the way, using Parent property to obtain reference to parent view may be incorrect in some cases, for example if your child view not placed parent directly. If it is, use following binding:{Binding Path=DataContext.mainDateTimeProperty, RelativeSource={RelativeSource Type=FindAncestor, AncestorType={x:Type uc:YourParentViewModelType}}}
STO