简体   繁体   中英

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. You have to apply the GLib.ConnectBeforeAttribute to the event handler.
  2. Creating a menu and calling it's Popup() method if the right mouse button was pressed.
  3. Handling the ButtonPressEvent of the menu item and using the NodeView's NodeSelection property to delete the node.

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;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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