Blog

All Blog Posts

Using the Tag Property during Silverlight Binding

I attended the DevConnections conference last week in Las Vegas.  Upon my return I immediately wanted to take Silverlight 4 for a test drive. So, I took my Silverlight 3 application and ran it through an upgrade process. The upgrade process worked fine, but a couple of things came to my attention.
  • I was using WCF RIA Services Beta. Lots of stuff has changed with the WCF RIA Services VS 2010 version. Here is a document outlining the breaking changes.
  • Using Binding to set the Name of my elements was not working.  I was doing the following binding within a ListBox. I started receiving an invalid XAML error when I ran the project. After a process of elimination I was able to pinpoint the issue with binding on x:Name. I tried binding on just "Name" but received the same issue.<TextBlock x:Name="{Binding businessID}" Text="{Binding busName}" MouseLeftButtonUp="TextBlock_MouseLeftButtonUp" />
Now the reason I applied binding to the Name element was so that I could retrieve the unique ID of the element in the ListBox when a user clicks the name to perform some automation. For example, if a user clicks on "My Accounting Firm" then I need to be able to get the unique ID of "My Accounting Firm" to apply some logic in the code behind.

My solution was to use the "Tag" property on the element to store the unique identifier of the business. This was a nice approach for me since I could store and pass data to the code-behind without the data being shown to the user in the UI. Here is the code from the XAML.
<TextBlock Text="{Binding busName}" Tag="{Binding businessID}" MouseLeftButtonUp="TextBlock_MouseLeftButtonUp" />
Here is the code from the on the Event Handler.
private void TextBlock_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    try
    {
        TextBlock business = (TextBlock)sender;
        if (business != null)
        {
            int businessID = 0;
            if (business.Tag != null)
            {
                string busID = business.Tag.ToString();
                //Do something cool here
            }
        }
    }
    catch (Exception ex)
    {
        //Handle exception
    }
}
This process worked great for me. I can now react to events and know with which items users are interacting. Keep coding my friends.