Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select TreeView item from code

Tags:

wpf

treeview

I have a three level treeview. How do I select any item in third level from code? I tried a method mentioned in many blogs and on stackoverflow but it seems to work only for first level (dbObject is null for items on below first level).

Here is the code I'm using to select TreeViewItem. Do I miss something?

public static void SetSelectedItem(this TreeView control, object item) {     try     {         var dObject = control.ItemContainerGenerator.ContainerFromItem(item);          //uncomment the following line if UI updates are unnecessary         ((TreeViewItem)dObject).IsSelected = true;          MethodInfo selectMethod = typeof(TreeViewItem).GetMethod("Select",             BindingFlags.NonPublic | BindingFlags.Instance);          selectMethod.Invoke(dObject, new object[] { true });     }     catch { } } 
like image 311
Sergej Andrejev Avatar asked Jun 02 '09 15:06

Sergej Andrejev


People also ask

How to set selected Item in TreeView WPF?

We can usually set TreeView's selected item by binding. In this case, if you need to set an item in the list as a selected item, you only need to set the corresponding Model. IsSelected to True.

How do I know if TreeView node is selected?

Solution 1Use TreeView. SelectedNode[^] property, which get or set selected node for currently selected Treeview. If no TreeNode is currently selected, the SelectedNode property is a null reference (Nothing in Visual Basic).

What is TreeView item?

TreeViewItem is a HeaderedItemsControl, which means its header and collection of objects can be of any type (such as string, image, or panel). For more information, see the HeaderedItemsControl class.

How do you bind TreeView?

The TreeView control supports declarative binding to an XML file by using XmlDataSource controls. You can bind a TreeView control to an XML file by creating an XmlDataSource control that represents the XML file and then assigning that XmlDataSource to your TreeView control.


1 Answers

Another option would be to use binding. If you have an object that you are using binding with to get the text of each TreeViewItem (for example), you can create a style that also binds the IsSelected property:

<TreeView>     <TreeView.Resources>         <Style TargetType="TreeViewItem">             <Setter Property="IsSelected"                     Value="{Binding Path=IsSelected, Mode=TwoWay}" />         </Style>     </TreeView.Resources> </TreeView> 

This assumes that the bound object has an IsSelected property of type bool. You can then select a TreeViewItem by setting IsSelected to true for its corresponding object.

The same approach can be used with the IsExpanded property to control when a TreeViewItem is expanded or collapsed.

like image 95
Andy Avatar answered Sep 24 '22 00:09

Andy