views:

39

answers:

2

I have a sub control embedded inside my main control, it allows the user to edit an address. Because this is reused all over the place (sometimes in multiple places on one control) I bind it like so

<Controls:EditAddressUserControl DataContext="{Binding Path=HomeAddress}"/>
<Controls:EditAddressUserControl DataContext="{Binding Path=WorkAddress}"/>

But the EditAddressUserControl needs access to the main control's list of CountrySummary objects so it can choose which country the address belongs to.

I have added a Countries DependencyProperty to EditAddressUserControl and added

Countries="{Binding Countries}"

So far all is going well, the EditAddressUserControl.Countries property has the correct countries in it. However, how do I databind my Combobox.ItemsSource to that in XAML?

I still want everything on my EditAddressUserControl to bind to its DataContext, but the ComboBoxCountries.ItemsSource needs to bind to "this.Countries".

How do I do that?

I've tried this

<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Controls:EditAddressUserControl}}, Path=Countries}" />

I saw no binding errors in the output box, but I also saw no items in the combobox.

+1  A: 

You can accomplish this by using a RelativeSource for the binding source, instead of the DataContext.

This would most likely look something like:

<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Controls:EditAddressUserControl}}, Path=Countries}" />
Reed Copsey
Tried it, but unfortunately it didn't work.
Peter Morris
This will work, provided you set it up correctly. You need to get the relative source to "find" the appropriate class in your ancestor hierarchy, where the DP is defined. I guessed on the syntax based on what you placed.
Reed Copsey
A: 

The way to do it was to stop using DataContext completely. Instead I added a DependencyProperty to my control

public static DependencyProperty AddressProperty = DependencyProperty.Register("Address", typeof(EditPostalAddressDto), typeof(EditPostalAddressControl));

Then in the parent control instead of setting DataContext="..." I set Address="..." - The XAML for the control is then changed to include an ElementName on the binding

<UserControl ..... x:Name="MainControl">
<TextBox Text="{Binding ElementName=MainControl,Path=Address.Region}"/>

Now I can specifically bind to the Address property, but also bind to properties on the main data context.

Peter Morris