Condividi tramite


Setting TreeView SelectedItem in Code

It is possible to set the selected item of a TreeView control in WPF without direct interaction with UI elements by including IsSelected property in your data object and binding it to IsSelected property of TreeViewItem. The code snippets below indicate how to set expanded and selected items of a TreeView control by updating the data that is bound to UI element.

- Define the style for TreeViewItem so that IsSelected and IsExpanded properties are bound to corresponding properties on the data:

Code Snippet:

<TreeView x:Name="TreeViewControl" ItemsSource="{Binding}">

    <TreeView.Resources>

        <HierarchicalDataTemplate DataType="{x:Type local:Item}" ItemsSource="{Binding Path=SubItems}">

          <TextBlock Text="{Binding Path=Name}"/>

        </HierarchicalDataTemplate>

        <Style TargetType="TreeViewItem">

            <Setter Property="IsSelected" Value="{Binding Path=IsSelected}"/>

            <Setter Property="IsExpanded" Value="{Binding Path=IsExpanded}"/>

        </Style>               

    </TreeView.Resources>

</TreeView>

 

- Define the Properties in your data class:

Code Snippet:

public class Item : INotifyPropertyChanged

{

    private string name;

    private bool isSelected;

    private bool isExpanded;

    public bool IsExpanded

    {

        get

        {

            return isExpanded;

        }

        set

        {

            isExpanded = value;

            this.OnPropertyChanged("IsExpanded");

        }

    }

    public bool IsSelected

    {

        get

        {

            return isSelected;

        }

        set

        {

            isSelected = value;

            this.OnPropertyChanged("IsSelected");

        }

    }

}

 

- Set the values in the Loaded method so that parent node is expanded and child node is selected when the treeview is displayed.

Code Snippet:

void Window1_Loaded(object sender, RoutedEventArgs e)

{

ObservableCollection<Item> items = new ObservableCollection<Item>();

Item item1 = new Item() {Name = "Item1"};

item1.SubItems.Add(new Item() {Name="Item1_1"});

items.Add(item1);

this.TreeViewControl.DataContext = items;

// Expand parent node and select the child node

item1.IsExpanded = true;

item1.SubItems[0].IsSelected = true;

}

 SettingTreeViewSelectedItemInCode

Comments

  • Anonymous
    July 06, 2008
    PingBack from http://blog.a-foton.ru/2008/07/setting-treeview-selecteditem-in-code/

  • Anonymous
    November 20, 2009
    Great and easy solution ;-). Thank you.

  • Anonymous
    February 22, 2010
    This didn't work for me.  I was hoping to use this approach to be able to deselect the selected tree item.  But my IsSelected setter never gets called when I select items in the treeview.   Has a real solution to this problem been implemented in WPF 4.0? Thanks, Eric

  • Anonymous
    March 20, 2010
    I've tried this WPF4 and it seems to be working. Are you trying to prevent selection of the items in treeview? You can find Item class definition that does this below (including the omitted parts this time) Note that in the setter of IsSelected value is ignored and it set to false so that the item will not be selected, even you click on the item in the UI. If you still have problems, please send me a repro.    public class Item : INotifyPropertyChanged    {        private string name;        private bool isSelected;        private bool isExpanded;        public string Name        {            get { return name; }            set { name = value; }        }        public bool IsExpanded        {            get { return isExpanded; }            set            {                isExpanded = value;                this.OnPropertyChanged("IsExpanded");            }        }        public bool IsSelected        {            get            { return isSelected; }            set            {                isSelected = false;  // originally = value                this.OnPropertyChanged("IsSelected");            }        }        public ObservableCollection<Item> SubItems        {            get;            private set;        }        public event PropertyChangedEventHandler PropertyChanged;        public Item()        {            SubItems = new ObservableCollection<Item>();        }        private void OnPropertyChanged(String info)        {            if (PropertyChanged != null)            {                PropertyChanged(this, new PropertyChangedEventArgs(info));            }        }    }

  • Anonymous
    November 16, 2010
    Is there a way to manually select a certain treeview item?

  • Anonymous
    November 17, 2010
    Hi Shimmy, The recommended approach is to bind it to a data object with IsSelected property as outlined in this blog. If you are required to work against TreeviewItem object directly, you might want to check out  askernest.com/.../how-to-programmatically-change-the-selecteditem-in-a-wpf-treeview.aspx

  • Anonymous
    December 08, 2012
    I haven't been successful at implementing that solution with the TreeViewItem style. After programmatically selecting an item, the selection seems to be reset to what was selected before. I have posted a related question with a ready-to-run sample that illustrates the problem over on StackOverflow: stackoverflow.com/.../synchronizing-a-selectedpath-property-with-the-selecteditem-in-wpfs-treeview