C# 将选定的 TreeView 节点滚动到视图中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/457932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 04:10:32  来源:igfitidea点击:

Scroll selected TreeView node into view

c#winformstreeview

提问by Brad

I have a System.Windows.Forms.TreeViewdocked inside a panel. I am setting a node selected programmatically. What method or property would I use to have the treeview scroll the selected into view?

我有一个System.Windows.Forms.TreeView停靠在面板内。我正在设置一个以编程方式选择的节点。我将使用什么方法或属性让树视图将选定的对象滚动到视图中?

采纳答案by Marc Gravell

node.EnsureVisible();

for example:

例如:

if(treeView.SelectedNode != null) treeView.SelectedNode.EnsureVisible();

(see MSDN)

(见MSDN

回答by peterincumbria

I had some issues with node.EnsureVisible()not working for trees with only one level of nodes.

我在node.EnsureVisible()处理只有一层节点的树时遇到了一些问题。

To fix this use the BindingIndexto identify the node selected. Then the node selected will be scrolled in view.

要解决此问题,请使用BindingIndex来标识所选节点。然后所选节点将在视图中滚动。

The example shows myTablefrom a LINQ query.

该示例myTable来自 LINQ 查询。

node.BindingIndex = Convert.ToInt32(mytable.Id);

I hope this helps some of you.

我希望这对你们中的一些人有所帮助。

回答by Folkien

I also had issues with this and figured out that treeview.ExpandAll() ignores the EnsureVisible() effect and avoids the scrolling to the node position.

我也遇到了这个问题,并发现 treeview.ExpandAll() 忽略了 EnsureVisible() 效果并避免滚动到节点位置。

Just call EnsureVisible() after ExpandAll() if you want a full expanded tree with the scroll on the node you've selected.

如果您想要一个完整展开的树并在您选择的节点上滚动,只需在 ExpandAll() 之后调用 EnsureVisible()。

回答by Joaquim Varandas

To ensure the visibility of selected item:

确保所选项目的可见性:

private void EnsureItemVisible()
{
    if(treeView1.SelectedNode == null)
    {
        return;
    }

    for (int i = treeView1.SelectedNode.Index + treeView1.VisibleCount / 2; i >= 0; i--)
    {
        if (treeView1.Nodes.Count > i && treeView1.Nodes[i] != null)
        {
            treeView1.Nodes[i].EnsureVisible();
            break;
        }
    }

    for (int i = treeView1.SelectedNode.Index - treeView1.VisibleCount / 2; i < treeView1.Nodes.Count; i++)
    {
        if (i >= 0 && treeView1.Nodes[i] != null)
        {
            treeView1.Nodes[i].EnsureVisible();
            break;
        }
    }
}

Handle the TreeView selection has been changed:

处理 TreeView 选择已更改:

private void TreeView_AfterSelect(object sender, TreeViewEventArgs e)
{   
    EnsureItemVisible();
}