Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove SelectedItem from TreeView

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

like image 818
Gabriel Avatar asked Dec 20 '11 13:12

Gabriel


1 Answers

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;
        }
    }
}
like image 111
Marat Khasanov Avatar answered Sep 20 '22 05:09

Marat Khasanov