Silverlight: Add a CheckBox to a TreeView and Handle Events

Let us see how to add controls like the CheckBox to a TreeView. Creating a TreeView is quite simple. You can either explicitly define items in the XAML file or bind data programmatically.

Just drag and drop a TreeView Control from the Toolbox and declare a couple of items as shown below:

silverlight treeview

OUTPUT

silverlight treeview preview

Now let us say you want to show some checkboxes in the TreeView control. To do so, you have to use the HeaderTemplate property and provide a DataTemplate as shown below:

treeview checkbox

As you can see, for the first node, we have used the HeaderTemplate property and added a DataTemplate inside it which shows the Checkbox, as shown below:

silverlight treeview checkbox

Note: If you are binding the TreeView programmatically, use a HierarchicalDataTemplate. Let me know if you need an example for that.

Binding Events to the CheckBox inside TreeView

If you observe, the checkbox has a click event attached to it. Let us add some code which will retrieve the Name of the node when the checkbox is clicked. Comments have been added to help you understand the code:

private void cb_Click(object sender, RoutedEventArgs e)
{
// Get parent item of clicked checkbox
TreeViewItem tvi = GetParentItem((DependencyObject)sender);
if (tvi != null)
{
// Display the Label of the CheckBox
MessageBox.Show(tvi.Header.ToString());
}

}

private static TreeViewItem GetParentItem(DependencyObject obj)
{
if (obj != null)
{
// Get the Object Parents Object in the Visual Tree
DependencyObject objParent = VisualTreeHelper.GetParent(obj);
// Cast it to TreeViewItem
TreeViewItem parentItem = objParent as TreeViewItem;
// recursive code
return (parentItem != null) ? parentItem : GetParentItem(objParent);
}
return null;
}

As soon as the checkbox is clicked, a MessageBox pops up showing the Label of the Node.

OUTPUT

treeview checkbox click

Note: If you have multiple checkboxes, create a generic handler and add the click code in it.






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

3 comments:

Suprotim Agarwal said...

oops! read Billionare as Billionaire :)

Mike Long said...

I would appreciate an example of HierarchicalDataTemplate. How about showing the same treeview with databinding minus the checkbox.

Cheers, Mike.

Suprotim Agarwal said...

Mike: Luckily I had a sample! Here's a post I just wrote. HTH

Silverlight TreeView DataBinding Example with HierarchicalDataTemplate