Friday 24 July 2009

Accessing and Identifying objects in Silverlight ItemTemplate

One simple way to identify and access objects within an ItemTemplate is to Bind the Name of the object of interest to a String variable that is passed as part of the DataContext and attach EventHanler to Loaded event. The EventHandler will then Store the objects received as sender of the event into a Dictionary keyed on the object's Name.

Here is an example With TreeView within ListBox:

<UserControl xmlns:Toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"  x:Class="silverlight.net.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
<Grid x:Name="LayoutRoot">
<ListBox x:Name="listBox" Margin="0,38,0,0" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Toolkit:TreeView x:Name="{Binding}" Loaded="TreeView_Loaded" ></Toolkit:TreeView>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button VerticalAlignment="Top" HorizontalAlignment="Center" Content="Load TreeView Items" Click="Button_Click"/>
</Grid>
</UserControl>



And Here is the code Behind:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace silverlight.net
{
public partial class MainPage : UserControl
{
Dictionary<System.String, TreeView> TreeViewChildren = new Dictionary<string,TreeView>();
List<String> ChildTreeViewNames = new List<string>();
public MainPage()
{
InitializeComponent();

List<String> ChildTreeViewNames = new List<string> { "TreeView1", "TreeView2" };
listBox.ItemsSource = ChildTreeViewNames;

}

private void TreeView_Loaded(object sender, RoutedEventArgs e)
{
TreeViewChildren.Add((System.String)((TreeView)sender).Name, (TreeView)sender);
}

private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
TreeViewChildren["TreeView1"].Items.Add(new TreeViewItem() { Header = "Item1" });
TreeViewChildren["TreeView1"].Items.Add(new TreeViewItem() { Header = "Item2" });
TreeViewChildren["TreeView2"].Items.Add(new TreeViewItem() { Header = "Item3" });
}
}
}

No comments: