Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF TreeView Clear Selection

Tags:

.net

wpf

treeview

How would I clear the TreeView selection within a WPF TreeView? I have tried looping through the TreeNodes and clearing the IsSelected property, however that is a ReadOnly property. Any ideas?

The TreeView is using XML Binding through the XMLDataProvider object.

like image 299
Luke Avatar asked Mar 24 '09 10:03

Luke


4 Answers

I came across the exact same problems and wrote the following code which will work on any treeview, with just a single line call to the first function.

class TomWrightsUtils
{
    public static void ClearTreeViewSelection(TreeView tv)
    {
        if (tv != null)
            ClearTreeViewItemsControlSelection(tv.Items, tv.ItemContainerGenerator);
    }
    private static void ClearTreeViewItemsControlSelection(ItemCollection ic, ItemContainerGenerator icg)
    {
        if ((ic != null) && (icg != null))
            for (int i = 0; i < ic.Count; i++)
            {
                TreeViewItem tvi = icg.ContainerFromIndex(i) as TreeViewItem;
                if (tvi != null)
                {
                    ClearTreeViewItemsControlSelection(tvi.Items, tvi.ItemContainerGenerator);
                    tvi.IsSelected = false;
                }
            }
    }
}
like image 182
Tom Wright Avatar answered Nov 02 '22 02:11

Tom Wright


Not sure what you mean by TreeNodes.

Typically you would have a corresponding IsSelected property on your view model that your view binds to:

<TreeView>
    <TreeView.ItemContainerStyle>
        <Style TargetType="TreeViewItem">
            <Setter Property="IsSelected" Value="{Binding IsSelected}"/>
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>

Therefore, you would just loop through the data items in your view model and set IsSelected = false there.

However, it sounds like you don't have such a property. That being the case, you need to get the corresponding TreeViewItem for each data item. See the TreeView.ItemContainerGenerator property for info on how to do this. Something like:

var treeViewItem = _treeView.ItemContainerGenerator.ContainerFromIndex(0) as TreeViewItem;
treeViewItem.IsSelected = false;
like image 38
Kent Boogaart Avatar answered Nov 02 '22 04:11

Kent Boogaart


TreeViewItem tvi = tvMain.ItemContainerGenerator.ContainerFromIndex(0) as TreeViewItem;

if (tvi != null) { tvi.IsSelected = true; tvi.IsSelected = false; }
like image 6
cpllael Avatar answered Nov 02 '22 02:11

cpllael


Find the selected item and set the value:

private void Button_Click(object sender, RoutedEventArgs e)
{
  TreeViewItem tvi = treeviewExample.SelectedItem as TreeViewItem;
  if (tvi != null)
  {
    tvi.IsSelected = false;
  }
}
like image 2
amaca Avatar answered Nov 02 '22 04:11

amaca