Skip to main content
 首页 » 编程设计

c#之C#中的树节点选择问题

2024年02月23日14mate10pro

每当我在树节点文本之外单击时,在控制部分,它会触发一个节点单击事件 - 但不会突出显示该节点。我不确定为什么会这样。

我希望通过单击选择节点 - 当您单击节点文本时 - 而不是空白 - 我只假设节点宽度达到整个树节点?我有 dock.fill 模式的 Treeview,如果这与它有关 - 我尝试了一切但无法让它正常运行。

也许有人会知道是怎么回事。

更新: 如果(e.Location.IsEmpty) {

似乎工作得更好 - 但仍然选择没有文本的空白处的节点 - 显然节点宽度似乎延伸到整个 TreeView ?

有没有更好的方法来完成我想要的?或者这是最好的方法?

更新:以前的想法行不通 - 唉 - 我以为它做到了,但事实并非如此。

新问题:我认为部分问题与现在从 TreeView 切换时的焦点有关。

更新-

我想出的关于在 beforeSelect 事件上禁用鼠标右键单击以选择节点的唯一代码是

 if (MouseButtons == System.Windows.Forms.MouseButtons.Right) 
            { 
                e.Cancel = true; 
 
            } 

但它没有用 - 任何帮助表示赞赏 - 遵循仅答案的建议,了解更多详细信息。

请您参考如下方法:

您应该使用 treeView.HitTest 方法来确定节点的哪一部分被点击。

private bool IsClickOnText(TreeView treeView, TreeNode node, Point location) 
{ 
    var hitTest = treeView1.HitTest(location); 
 
    return hitTest.Node == node 
        && hitTest.Location == TreeViewHitTestLocations.Label; 
} 
 
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) 
{ 
    if(IsClickOnText(treeView1, e.Node, e.Location)) 
    { 
        MessageBox.Show("click"); 
    } 
} 
 
private void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e) 
{ 
    if (e.Action == TreeViewAction.ByMouse) 
    { 
        var position = treeView1.PointToClient(Cursor.Position);         
        e.Cancel = !IsClickOnText(treeView1, e.Node, position); 
    } 
}