How do I bind to a RelativeSource Self?

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 noticed that I used two different binding methods here. Those who use the Element Name work, and the other does not. Here is the 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 for the most part. I want my binding to work with:

 {Binding Description} 

Instead:

 {Binding Path=Description, ElementName=_UserInputOutput} 

It seems to work only when using ElementName. I need to export / import this XAML, so I cannot have ElementName or import will not work.

I thought this would be best:

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

This did not work.

Any ideas? Thank!

+13
wpf binding
Aug 16 '12 at 20:57
source share
2 answers

You have not set up a DataContext that uses a RelativeSource to determine what this refers to. You need to set the DataContext to a higher level, such as UserControl. I usually have:

 <UserControl ... DataContext="{Binding RelativeSource={RelativeSource Self}}"> </UserControl> 

This tells UserControl to bind itself to the class in code.

+26
Aug 16 2018-12-12T00:
source share

{RelativeSource Self} sets the object to which the related property belongs, if you have such a binding on a Label , it will look for a Label.Description that does not exist. Instead, you should use {RelativeSource AncestorType=UserControl} .

ElementName bindings ( ElementName , Source , RelativeSource ) are related to the DataContext , however in UserControls you should avoid setting the DataContext so as not to damage the external bindings.

+29
Aug 16 2018-12-12T00:
source share



All Articles