Peter Morris
Peter Morris

Reputation: 23284

How do I databind to the control's property rather than the datacontext?

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.

Upvotes: 1

Views: 208

Answers (2)

Peter Morris
Peter Morris

Reputation: 23284

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.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564891

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}" />

Upvotes: 1

Related Questions