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

时间:2009-06-04 17:33:36

标签: c# contextmenu gtk#

我想在树节点上添加一个上下文菜单,允许我删除该树节点。

1 个答案:

答案 0 :(得分:5)

可以通过以下方式完成:

  1. 处理NodeView的ButtonPressEvent。您必须将GLib.ConnectBeforeAttribute应用于事件处理程序。
  2. 如果按下鼠标右键,则创建一个菜单并调用它的Popup()方法。
  3. 处理菜单项的ButtonPressEvent并使用NodeView的NodeSelection属性删除节点。
  4. 从空窗口开始,代码如下所示:

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