Click here to Skip to main content
15,896,269 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I created a UserControl which has a ComboBox within it that I would like to expose so I can bind to the ComboBox from within the MainWindow.xaml when I add the UserControl. I found the below code, which works, but I don't understand why/what is actually going on.

XML
<ComboBox HorizontalAlignment="Left" Margin="38,2,0,0" VerticalAlignment="Top" Width="120" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Views:UserControl1, AncestorLevel=1}, Path=ComboBox1ItemsSource}" />


**(Views) is a XAML defined namespace to my Views directory.

I would've though I could have just set the ItemsSource to:
XML
ItemsSource = "{Binding RelativeSource={RelativeSource Self}, Path=ComboBox1ItemsSource}"


Why wouldn't setting the source to Self work? What is going on when the using the FindAcestor as shown in the first bit of code above.

Also in case it is important, I did have to add the following code behind for the first bit of code to work.

C#
public static readonly DependencyProperty ComboBox1ItemsSourceProperty;

public IEnumerable ComboBox1ItemsSource { get; set; }

static UserControl1()
{
   ComboBox1ItemsSourceProperty = DependencyProperty.Register("ComboBox1ItemsSource", typeof(IEnumerable), typeof(UserControl1));
}
Posted

1 solution

Using RelativeSource tells the binding to ignore the current DataContext, and try to find the specified property on a particular element instead.

Setting {RelativeSource Self} would attempt to find a property called ComboBox1ItemsSource on the ComboBox itself. Since the ComboBox doesn't have a property with that name, the binding would fail.

Using {RelativeSource FindAncestor, ...} walks up the logical tree to find the nearest UserControl1, and tries to use the ComboBox1ItemsSource property from that instance.

The remarks on the MSDN documentation for the RelativeSource markup extension[^] have a decent explanation of the various options.
 
Share this answer
 
Comments
MrGlass3 9-Feb-15 11:41am    
Oh I guess I didn't understand the use of 'Self' I thought that referred to the whole instance of the XAML view, in the way that 'this' refers to the instance of that class in C#.

Thanks!

Is there a keyword that allows you to refer to the whole View object?
Richard Deeming 9-Feb-15 11:44am    
I don't think there's anything simpler than the FindAncestor approach to refer to the parent UserControl.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900