In this blog we will learn how to clear/deselect selected items in TreeView while working on a WPF application. There following scenarios need to be considered before coming up for a solution to the problem:
1) The TreeView is bound to a SelectedItem which is itself an item of a binded collection.
2) There are multiple levels of ItemContainerGenerator which may contain deeper level objects
To solve the above problem we will loop recursively through the whole TreeView and set the IsSelected property to false. Following is a class that implements the logic to deselect the items.
// This class is used for clearing selection in treeView
class ClearTreeSelection
{
public static void ClearTreeViewSelection(TreeView tview)
{
if (tview != null)
ClearTreeViewItemsControlSelection(tview.Items, tview.ItemContainerGenerator);
}
private static void ClearTreeViewItemsControlSelection(ItemCollection ic, ItemContainerGenerator icg)
{
if ((ic != null) && (icg != null))
for (int i = 0; i < ic.Count; i++)
{
// Get the TreeViewItem
TreeViewItem tvi = icg.ContainerFromIndex(i) as TreeViewItem;
if (tvi != null)
{
//Recursive call to traverse deeper levels
ClearTreeViewItemsControlSelection(tvi.Items, tvi.ItemContainerGenerator);
//Deselect the TreeViewItem
tvi.IsSelected = false;
}
}
}
}
Hope the above blog helped in solving a common problem encountered in working with TreeView in a WPF application.
0 Comment(s)