Silverlight Tips provides simple and useful tutorials and tips with real life examples, live demos and sample codes to download.
About authors:
Damon Serji
Damon Serji,
Silverlight developer working at Metia in London.
Gavin Wignall
Gavin Wignall,
Interactive Design Lead, working in design for over 10 years, the last 3 being in Silverlight.
Allan Muller
Allan Muller,
Developer, working on various types of Silverlight and WCF projects.

this post will give you answer to below questions:

  • How to find/target a Silverlight control which was added through a DataTemplate of a list-based control such as ItemsControl, ComboBox, ListBox or etc.
  • Use Tag property in Silverlight controls to identify different items

In order to identify different controls in your ItemsControl, you could assign a unique identifier (ID) to each control through the "Tag" property.


<ListBox x:Name="lb_test" Width="200" Height="200"
         VerticalAlignment="Top" ItemsSource="{Binding}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Width="190" Tag="{Binding Id}" Text="{Binding Name}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Code behind for adding the data:

private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    List<Items> itemsList = new List<Items>();
    Items it = new Items();
    it.Name = "Damon";
    it.Id = 1;
    itemsList.Add(it);
    Items it2 = new Items();
    it2.Name = "Allan";
    it2.Id = 2;
    itemsList.Add(it2);
    Items it3 = new Items();
    it3.Name = "Rachel";
    it3.Id = 3;
    itemsList.Add(it3);
    lb_test.ItemsSource = itemsList;
}

Create a new class called Items to store Name and Id
public class Items
{
    public string Name {get; set;}
    public int Id { get; set; }
}

and the result:

Now we need to find items inside the ListBox control and apply whatever code we want to them. Here I am going to find the TextBlock for Allan thought the ID I gave it (2) and add an MouseLeftButtonUp event to it, so when we click on Allan we get an alert popup.

First thing we need to do is to add the following line to the end of our MainPage_Loaded method (after the ItemsSource of our ListBox is assigned):

CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);

Above line will re-render you layout to force any updates you have done after your xaml was initially rendered.

And here is the method that is called through the above code:

private void CompositionTarget_Rendering(object sender, EventArgs e)
{
    AddEventHandlers(lb_test, -1);
}

And finally the method to find the TexBlock we are looking for, and adding the EventHandler:

private void AddEventHandlers(DependencyObject parent, int childIndex)
{
    DependencyObject child;
    TextBlock textBlock;
    int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
    if (parent == lb_test && childrenCount > 0)
    {
        CompositionTarget.Rendering -= CompositionTarget_Rendering;
    }
    for (int index = 0; index < childrenCount; index++)
    {
        child = VisualTreeHelper.GetChild(parent, index);
        if (child is TextBlock)
        {
            textBlock = (TextBlock)child;
            if (textBlock.Tag != null)
            {
                int id = (int)textBlock.Tag;
                if (id == 2)
                {
                    textBlock.MouseLeftButtonUp +=
                    new MouseButtonEventHandler(textBlock_MouseLeftButtonUp);
                    textBlock.Foreground = new SolidColorBrush(Colors.Green);
                }
            }
        }
        else if (child is ContentPresenter)
        {
            AddEventHandlers(child, index);
        }
        else
        {
            AddEventHandlers(child, childIndex);
        }
    }
}

private void textBlock_MouseLeftButtonUp(object sender
, MouseButtonEventArgs e)
{
    TextBlock tb = sender as TextBlock;
    if (tb != null)
    {
        System.Windows.Browser.HtmlPage.Window.Alert(tb.Text + " was
        clicked!"
);
    }
}

In summary, we are passing the x:Name of our ListBox "parent" to the AddEventHandlers and search in its children for any TextBlock controls. If we didn’t find any TextBlock we search in any other searchable controls we find inside that and we do that again until we find all TextBlocks or there is no more controls to search within.

When we find a TextBlock, we check if it has a Tag property and if the value is what we were looking for, if true, we simply add or EventHandler, change color, or do anything we want to do to that TextBlock.

Download the working version of the entire project from here.

Posted by Damon Serji on 30. August 2009 20:02 under: Intermediate
 with 0 Comments

How to programmatically add a 'mailto' link in silverlight:

Add the below line to your .xaml.cs file to open mailto (email link) when an event gets fired (i.e. HyperlinkButton is clicked or etc):

HtmlPage.Window.Navigate(new Uri("mailto:tips@silverlighttips.com"));

if HtmlPage is not recognised in your Visual Studio, it is because you are missing an assemblly reference, so simply add this reference to the very top of your page:

using System.Windows.Browser;

Posted by Damon Serji on 24. August 2009 16:44 under: Basic
 with 5 Comments