How to programmatically select an item in a WPF TreeView?

后端 未结 16 2296
时光取名叫无心
时光取名叫无心 2020-11-28 08:42

How is it possible to programmatically select an item in a WPF TreeView? The ItemsControl model seems to prevent it.

16条回答
  •  醉梦人生
    2020-11-28 09:09

    Just thought I would chime in with the solution I went with, in case this can help anyone. Note that the best way to do this is using a bound property like 'IsSelected' as per kuninl's answer, but in my case it was a legacy application that did not follow MVVM, so I ended up with the below.

    private void ChangeSessionSelection()
    {
        foreach (SessionContainer item in this.treeActiveSessions.Items)
        {
            var treeviewItem = this.treeActiveSessions.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
    
            if (item.Session == this.selectedSession.Session)
            {
                treeviewItem.IsSelected = true;
                treeviewItem.IsExpanded = true;
            }
            else
            {
                treeviewItem.IsSelected = false;
                treeviewItem.IsExpanded = false;
            }
        }            
    }
    

    What this does is select and expand the treeview item in the UI that represents the selected dataitem in the code behind. The purpose of this was to have the selection change in the treeview when the users selection changed in an items control in the same window.

提交回复
热议问题