2013-08-06 46 views
2

我希望我問正確的問題,但這是我的情況。我有一個TreeViewItem,我正在實施。在裏面我設置/添加各種屬性,其中之一是ContextMenu。我想要做的就是將MenuItems添加到ContextMenu而不傳遞給函數等。在實施過程中是否可以將菜單項添加到上下文菜單?

以下是我實現我TreeViewItemContextMenu

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

非常感謝!

回答

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); 
+0

我接受了這個答案,因爲它是我用來讓我的程序工作的人。非常感謝你。 –

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; 

你可以將其設置爲支持這樣的元素。

編輯:我正在寫它的記憶,抱歉,如果它不是確切的。但或多或少就是這個想法。

+0

這將幫助我添加事件到這些項目,非常感謝! –

相關問題