Remove SelectedItem from TreeView

13,746

Solution 1

Not sure what you mean

If you want to remove the item, use this:

treeView1.Items.Remove(treeView1.SelectedItem);

If you want to remove the selection from the treeview, use this:

((TreeViewItem)treeView1.SelectedItem).IsSelected = false;

Solution 2

All previous answers will be helpful when you build the TreeView explicitly using TreeViewItem(s). If you need a solution to clear selection when using ItemsSource, use the following code:

private static TreeViewItem FindTreeViewSelectedItemContainer(ItemsControl root, object selection)
{
    var item = root.ItemContainerGenerator.ContainerFromItem(selection) as TreeViewItem;
    if (item == null)
    {
        foreach (var subItem in root.Items)
        {
            item = FindTreeViewSelectedItemContainer((TreeViewItem)root.ItemContainerGenerator.ContainerFromItem(subItem), selection);
            if (item != null)
            {
                break;
            }
        }
    }

    return item;
}

// Example:
private void Button_Click(object sender, RoutedEventArgs e)
{
    if (TV.SelectedItem != null)
    {
        var container = FindTreeViewSelectedItemContainer(TV, TV.SelectedItem);
        if (container != null)
        {
            container.IsSelected = false;
        }
    }
}

Solution 3

You want to unselect what is selected?

I think you want something like this:

((TreeViewItem)tv.SelectedItem).IsSelected = false;
Share:
13,746
Gabriel
Author by

Gabriel

Works backend with PHP and Web services(REST/SOAP).

Updated on July 23, 2022

Comments

  • Gabriel
    Gabriel almost 2 years

    Is there a simple way to set a TreeView's SelectedItem to null or equivalent? Also, I need to do this in C# and not in XAML.

    Best regards,

    Gabriel

  • Ray
    Ray over 12 years
    SelectedItem is an object so you need to cast it.
  • Marat Khasanov
    Marat Khasanov over 12 years
    What will you do if TreeView is data bound?
  • Gabriel
    Gabriel over 12 years
    Of course, I didn't think about that you could deselect using IsSelected property. Silly of me, excellent answer. Works like a charm, cheers!
  • abc
    abc over 12 years
    there was no hint to that in the question, so i guess he's building the treeview on his own ;)
  • EvAlex
    EvAlex over 11 years
    Try to click on the deselected item and you will be surprised. Also try to switch to another window and then back to browser. The "deselected" item becomes selected