C# TreeView 标签编辑问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/181928/
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-03 16:55:35  来源:igfitidea点击:

TreeView label editing question

c#treeview

提问by neo2862

I have a treeview with nodes like this: "Foo (1234)", and want to allow the user to rename the nodes, but only the Foo part, without (1234). I first tried to change the node text in BeforeLabelEditlike this:

我有一个带有如下节点的树视图:“Foo (1234)”,并希望允许用户重命名节点,但只重命名 Foo 部分,而没有 (1234)。我首先尝试BeforeLabelEdit像这样更改节点文本:

private void treeView1_BeforeLabelEdit(object sender, NodeLabelEditEventArgs e)
{
    e.Node.Text = "Foo";
}

But when I click the node to edit it, "Foo (1234)" appears in the textbox.

但是当我单击节点进行编辑时,文本框中会出现“Foo (1234)”。

Okay, then let's try something else.

好的,那我们再试试别的。

I set treeView1.LabelEditto false, and then do the following:

我设置treeView1.LabelEdit为false,然后执行以下操作:

private void treeView1_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        if (treeView1.SelectedNode == treeView1.GetNodeAt(e.Location))
        {
            treeView1.SelectedNode.Text = "Foo";
            treeView1.LabelEdit = true;
            treeView1.SelectedNode.BeginEdit();
        }
    }
}

And then in AfterLabelEdit, I set LabelEditback to false.

然后在 中AfterLabelEdit,我LabelEdit重新设置为 false。

And guess what? This doesn't work either. It changes the node text to "Foo" but the edit textbox does not appear.

你猜怎么着?这也行不通。它将节点文本更改为“Foo”,但不会出现编辑文本框。

Any ideas? Thanks

有任何想法吗?谢谢

采纳答案by neo2862

Finally I have found a solutionto this on CodeProject. Among the comments at the bottom, you will also find a portable solution.

最后,我在CodeProject上找到了解决方案。在底部的评论中,您还将找到一个便携式解决方案。

回答by Matt Hamilton

Heh - I struck that one a few years back. I even left a suggestion on Connect(vote for it!) to allow the label to be changed in BeforeLabelEdit.

呵呵 - 几年前我打过那个。我什至在 Connect 上留下了一个建议(投赞成票!)以允许在 BeforeLabelEdit 中更改标签。

One option (in WinForms - it's a different story in WPF) is to use custom painting for your TreeNodes so that the actual label is still "Foo" and you custom draw the " (1234)" after it. It's a bit of a pain to get right though.

一种选择(在 WinForms 中 - 在 WPF 中是另一回事)是为您的 TreeNode 使用自定义绘画,以便实际标签仍然是“Foo”,并且您在其后自定义绘制“(1234)”。不过,做对有点痛苦。