Sometimes, we need to bind the same data to different properties of the same control. For example, in some cases, we need to show text in a TextBlock
and also want to show the same text as a tooltip to that TextBlock
control.
How do we do it? It's very easy to bind the same value twice in the control. But is there any other way to implement this? Let us discuss this today in this blog post. If you were not aware of this till date, you will definitely like this.
Let us see the most common way to implement this. We can bind the same data to multiple properties of the same control like this:
<TextBlock Text="{Binding Information, ElementName=userControl}"
ToolTipService.ToolTip="{Binding Information, ElementName=userControl}"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
If you want to do this in a similar way, you have to define a name for the UserControl
or the TextBlock
control itself and use that as the ElementName
explicitly.
In other ways, you can use the RelativeSource
binding in XAML to self bind the same data to multiple properties like Text
and Tooltip
, as below:
<TextBlock Text="{Binding Information, ElementName=userControl}"
ToolTipService.ToolTip="{Binding Text, RelativeSource={RelativeSource Self}}"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
You will notice that the data binding mentioned here uses RelativeSource
. Generally, this property is used to bind one property of one object to another property of the same object like we defined in the above code snippet. Here, the word "Self
" is a string
token that has been set as the Mode
of the RelativeSource
binding.
Hope this will help you if you were not aware of it already.
Thanks for reading this tip.
Cheers.
Download the source code of the entire solution from RelativeSource demo (source code) - 23 KB
Reference