0
我試圖從主菜單欄創建一個嵌套菜單層次結構。例如,主菜單欄將包含一個可以導航爲「轉到」 - >「章節」 - >「章節名稱」 - >「分節名稱」的「轉到」菜單項。嵌套得太深時WPF菜單消失
「章節」下面的層次需要動態添加。當我這樣做時,菜單會在試圖顯示章節名稱的子項時消失。
如果您運行下面的代碼示例,您可以單擊「轉到」和「章節」,但只要將鼠標懸停在上面或單擊其中一個章節名稱,菜單就會消失,而不允許其中一個小節名稱被點擊。
有誰能告訴我爲什麼?
using System;
using System.Windows;
using System.Windows.Controls;
namespace MenuTest
{
public class MenuTest : Window
{
// Main method
[STAThread]
public static void Main()
{
Application App = new Application();
App.Run(new MenuTest());
}
// Properties:
Menu MainMenu;
MenuItem GotoMenu;
MenuItem ChapterMenu;
// Constructor
public MenuTest()
{
// Add a menu with a "Goto" submenu that opens up a pop-up with a "Chapter" selection:
// ----------------------------------------------------------------------------------
MainMenu = new Menu();
DockPanel.SetDock(MainMenu, Dock.Top);
this.Content = MainMenu;
GotoMenu = new MenuItem();
GotoMenu.Header = "Goto";
GotoMenu.SubmenuOpened += OnSubMenuOpen;
MainMenu.Items.Add(GotoMenu);
ChapterMenu = new MenuItem();
ChapterMenu.Header = "Chapter";
GotoMenu.Items.Add(ChapterMenu);
}
// Add a chapter and subchapter hiearachy to the Chapter menu:
void OnSubMenuOpen(object Sender, RoutedEventArgs e)
{
ChapterMenu.Items.Clear();
string[] ChapterNames = { "Chapter 1", "Chapter 2", "Chapter 3" };
foreach (string ChapterName in ChapterNames)
{
MenuItem ThisChapterMenu = new MenuItem();
ThisChapterMenu.Header = ChapterName;
ChapterMenu.Items.Add(ThisChapterMenu);
string[] SubChapterNames = { "SubSection 1", "SubSection 2", "SubSection 3" };
foreach (string SubChapterName in SubChapterNames)
{
MenuItem SectionMenu = new MenuItem();
SectionMenu.Header = String.Format("{0} - {1}", ChapterName, SubChapterName);
ThisChapterMenu.Items.Add(SectionMenu);
}
}
}
}
}
優秀的,就像一個魅力吧!非常感謝! – 2009-11-26 21:57:18