RelativeSource Binding in Silverlight

Sometime we need to bind the same data in 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 to do it? It's very easy to bind the same value twice in the control. But is there any other way to implement the same? Let us discuss this today in this blog post. If you are not aware of it till date, you will definitely like.



Let us discuss the common way to implement this. As we discussed we can bind data in 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 similar way, you have to define a name to the UserControl or to the TextBlock control itself and use that as "ElementName" explicitly.


In other way, you can use the RelativeSource binding in XAML to self binding the same data in 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 can notice that the data binding mentioned here uses the RelativeSource. Generally this property is used to bind one property of one object to the another property of the same object that 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 are not aware of it already. Thanks for reading this tip. Cheers. Download the Source code of the entire solution from here:  Relative Source Demo (Source Code) - 23 KB


Reference:  Binding.RelativeSource Property (MSDN)

External Publications (Outreach / Editorial)
Join Us