Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bind to RelativeSource Self?

Tags:

I am trying to bind several different properties in my Xaml:

<Label Content="{Binding Description}"  Visibility="{Binding Path=DescriptionVisibility,  ElementName=_UserInputOutput}"                FontSize="{Binding Path=FontSizeValue, ElementName=_UserInputOutput}"   HorizontalAlignment="Left" VerticalAlignment="Top" Padding="0" /> 

You will noticed I have used two Different binding techniques here. The ones using Element Name work, the other does not. Here is code behind:

public string Description {      get { return (string)GetValue(DescriptionProperty); }      set { SetValue(DescriptionProperty, value); } } public static readonly DependencyProperty DescriptionProperty =  DependencyProperty.Register("Description", typeof(string), typeof(UserControl),  new UIPropertyMetadata("")); 

Each Binding has a different name but they all look like this for the most part. I want my Binding to be able to work with:

{Binding Description} 

Instead of:

{Binding Path=Description, ElementName=_UserInputOutput} 

It only seems to be working when ElementName is used. I need to export/import this XAML, so I can't have a ElementName or the import won't work.

I thought this would be best:

{Binding Path=Description, RelativeSource={RelativeSource Self}} 

This did not work.

Any ideas?? Thank you!

like image 594
B-Rad Avatar asked Aug 16 '12 20:08

B-Rad


People also ask

What is RelativeSource Self?

{RelativeSource Self} targets the object that owns the property that is being bound, if you have such a binding on a Label it will look for Label. Description , which isn't there. Instead you should use {RelativeSource AncestorType=UserControl} .

What is binding path in WPF?

Binding path syntax. Use the Path property to specify the source value you want to bind to: In the simplest case, the Path property value is the name of the property of the source object to use for the binding, such as Path=PropertyName . Subproperties of a property can be specified by a similar syntax as in C#.


1 Answers

{RelativeSource Self} targets the object that owns the property that is being bound, if you have such a binding on a Label it will look for Label.Description, which isn't there. Instead you should use {RelativeSource AncestorType=UserControl}.

Bindings without a source (ElementName, Source, RelativeSource) are relative to the DataContext, however in UserControls you should avoid setting the DataContext to not mess with external bindings.

like image 113
H.B. Avatar answered Sep 28 '22 09:09

H.B.