2

我希望我问的是正确的问题,但这是我的情况。我有一个TreeViewItem我正在实施的。在其中我设置/添加各种属性,其中一个是ContextMenu. 我想要做的就是添加MenuItemsContextMenu而不传递给函数等。

这是我如何实现我的TreeViewItemwith ContextMenu

public static TreeViewItem Item = new TreeViewItem() //Child Node
{
        ContextMenu = new ContextMenu //CONTEXT MENU
        {
            Background = Brushes.White,
            BorderBrush = Brushes.Black,
            BorderThickness = new Thickness(1),

            //**I would like to add my MENUITEMS here if possible
        }
};

非常感谢!

4

2 回答 2

2

为此,WPF我这样做了:

TreeViewItem GreetingItem = new TreeViewItem()
    {
        Header = "Greetings",
        ContextMenu = new ContextMenu //CONTEXT MENU
        {
            Background = Brushes.White,
            BorderBrush = Brushes.Black,
            BorderThickness = new Thickness(1),
        }
    };

// Create ContextMenu
contextMenu = new ContextMenu();
contextMenu.Closing += contextMenu_Closing;

// Exit item
MenuItem menuItemExit = new MenuItem
{
      Header = Cultures.Resources.Exit,
      Icon= Cultures.Resources.close
};
menuItemExit.Click += (o, a) =>
{
     Close();
}

// Restore item
MenuItem menuItemRestore = new MenuItem
{
    Header = Cultures.Resources.Restore,
    Icon= Cultures.Resources.restore1
};
menuItemRestore.Click += (o, a) =>
{
     WindowState = WindowState.Normal;
};

contextMenu.Items.Add(menuItemRestore);
contextMenu.Items.Add(menuItemExit);               

GreetingItem.ContextMenu = contextMenu;

您可以将其设置为任何支持它的元素。

编辑:我是凭记忆写的,如果不准确,请见谅。但或多或少是这样的想法。

于 2013-08-06T12:49:55.240 回答
1

Sonhja的答案是正确的。为您的案例提供示例。

        TreeViewItem GreetingItem = new TreeViewItem()
        {
            Header = "Greetings",
            ContextMenu = new ContextMenu //CONTEXT MENU
            {
                Background = Brushes.White,
                BorderBrush = Brushes.Black,
                BorderThickness = new Thickness(1),
            }
        };

        MenuItem sayGoodMorningMenu = new MenuItem() { Header = "Say Good Morning" };
        sayGoodMorningMenu.Click += (o, a) =>
        {
            MessageBox.Show("Good Morning");
        };
        MenuItem sayHelloMenu = new MenuItem() { Header = "Say Hello" };
        sayHelloMenu.Click += (o, a) =>
            {
                MessageBox.Show("Hello");
            };
        GreetingItem.ContextMenu.Items.Add(sayHelloMenu);
        GreetingItem.ContextMenu.Items.Add(sayGoodMorningMenu);
        this.treeView.Items.Add(GreetingItem);
于 2013-08-06T12:54:00.357 回答