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=""

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

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;

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

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: