TreeView.SelectedNode设置后节点未高亮的技术求助
Hey Dave, I’ve dealt with this exact TreeView quirk before—it’s so annoying when the backend says the node is selected but the UI doesn’t show that highlight! Let’s walk through the most common fixes to get this working:
Check the
HideSelectionProperty
By default, WinForms TreeView hasHideSelectionset totrue, which means selected nodes stop showing their highlight when the TreeView loses focus. If you want the highlight to stay visible even when the control isn’t focused, just toggle this property off:yourTreeView.HideSelection = false;This is usually the quickest fix for persistent highlighting.
Give the TreeView Focus
If you want to keep the defaultHideSelectionbehavior (only highlight when the TreeView is active), make sure to set focus to the control right after settingSelectedNode:yourTreeView.SelectedNode = targetNode; yourTreeView.Focus();This ensures the TreeView has focus, so the selected node will show its highlight as expected.
Trigger Node Visibility (and UI Update)
If the target node is outside the currently visible area of the TreeView, callingEnsureVisible()will scroll to the node and often force the UI to update the highlight state:yourTreeView.SelectedNode = targetNode; targetNode.EnsureVisible();Force a Control Refresh (Last Resort)
In rare cases, the TreeView might not redraw immediately. A manual refresh can kickstart the UI update:yourTreeView.SelectedNode = targetNode; yourTreeView.Refresh();
Most of the time, the first two fixes will solve your problem. Start with checking HideSelection—it’s the most common culprit here!
内容的提问来源于stack exchange,提问作者David Thielen

