Using Element to Element Binding for ToolTips in Silverlight 3

Silverlight 3 provides a new feature called “element to element” binding that allows one element to bind to another element’s property.  It’s really useful when you want to tie two objects together so that when one object changes the other changes as well.

A lot of the samples I see for this new technology tend to focus on using slider controls but I just don’t have a need for sliders most of the time (although it certainly depends upon what type of application you’re building).  Here’s a simple yet effective way to leverage element to element binding for tooltips.  I currently have a ComboBox control with a data template and want to show a description of the selected item as the user mouses over the control.  With Silverlight 2 you’d have to write code since there wouldn’t be a way for the tooltip service to bind to the selected item declaratively.  Now, you can do something like this (notice the ToolTipService attribute):

<ComboBox 
    x:Name="WorkCodeComboBox"
    ItemsSource="{Binding Source={StaticResource ViewModel},Path=CurrentTimeSheetView.WorkCodes}"
    Style="{StaticResource TimeSheetComboBoxStyle}" 
    SelectionChanged="WorkCode_SelectionChanged"
    ToolTipService.ToolTip="{Binding Path=SelectedItem.Description, ElementName=WorkCodeComboBox}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Margin="0">
                <TextBlock Text="{Binding WorkCodeID}" Width="30" Margin="5,0,0,0" />
                <Rectangle Style="{StaticResource ComboBoxVerticalLine}" />
                <TextBlock Text="{Binding Description}" Width="250" Margin="10,0,0,0" />
            </StackPanel>
        </DataTemplate>
   </ComboBox.ItemTemplate>
</ComboBox>


In this case I’m binding the tooltip to the selected item’s Description property.  At first glance it looks like the ComboBox is binding to itself but in reality it’s binding to the ToolTipService’s Tooltip property.  A simple little trick but nice when you need it since it saves a line or two of C# code.

 

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit http://www.thewahlingroup.com/.

comments powered by Disqus

6 Comments

Comments have been disabled for this content.