Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • WPF : Deselect items in TreeView

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.20k
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: