简体   繁体   English

如何在Gtk#中将上下文菜单添加到树节点?

[英]How can I add a context menu to a tree node in Gtk#?

我想将上下文菜单添加到树节点,从而允许我删除该树节点。

It can be done by: 可以通过以下方式完成:

  1. Handling the ButtonPressEvent of the NodeView. 处理NodeView的ButtonPressEvent。 You have to apply the GLib.ConnectBeforeAttribute to the event handler. 您必须将GLib.ConnectBeforeAttribute应用于事件处理程序。
  2. Creating a menu and calling it's Popup() method if the right mouse button was pressed. 如果按下鼠标右键,则创建一个菜单并调用它的Popup()方法。
  3. Handling the ButtonPressEvent of the menu item and using the NodeView's NodeSelection property to delete the node. 处理菜单项的ButtonPressEvent并使用NodeView的NodeSelection属性删除该节点。

Starting with an empty window the code would look like this: 从一个空窗口开始,代码如下所示:

using System;
using Gtk;

public partial class MainWindow: Gtk.Window
{   
    NodeView myNodeView;
    NodeStore store;

    public MainWindow (): base (Gtk.WindowType.Toplevel)
    {
        Build ();

        store = new Gtk.NodeStore (typeof (MyTreeNode));
        store.AddNode (new MyTreeNode ("Item A"));
        store.AddNode (new MyTreeNode ("Item B"));
        store.AddNode (new MyTreeNode ("Item C"));

        myNodeView = new NodeView(store);
        myNodeView.ButtonPressEvent += new ButtonPressEventHandler(OnItemButtonPressed);

        myNodeView.AppendColumn ("Deletable items", new Gtk.CellRendererText (), "text", 0);
        myNodeView.ShowAll ();
        Add (myNodeView);
    }

    [GLib.ConnectBeforeAttribute]
    protected void OnItemButtonPressed (object sender, ButtonPressEventArgs e)
    {
        if (e.Event.Button == 3) /* right click */
        {
            Menu m = new Menu();
            MenuItem deleteItem = new MenuItem("Delete this item");
            deleteItem.ButtonPressEvent += new ButtonPressEventHandler(OnDeleteItemButtonPressed);
            m.Add(deleteItem);
            m.ShowAll();
            m.Popup();
        }
    }                                                           

    protected void OnDeleteItemButtonPressed (object sender, ButtonPressEventArgs e)
    {
        MyTreeNode node = (MyTreeNode)myNodeView.NodeSelection.SelectedNode;
        store.RemoveNode(node);
    }

    protected void OnDeleteEvent (object sender, DeleteEventArgs a)
    {
        Application.Quit ();
        a.RetVal = true;
    }
}

public class MyTreeNode : Gtk.TreeNode {

    public MyTreeNode (string text)
    {
        ItemText=text;
    }

    [Gtk.TreeNodeValue (Column=0)]
    public string ItemText {get; set;}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM