嵌套太深时,WPF菜单会消失

时间:2009-11-26 21:08:30

标签: c# wpf menu nested menuitem

我正在尝试从主菜单栏创建嵌套菜单层次结构。例如,主菜单栏将包含“Goto”菜单项,可以将其导航为“Goto” - > “章节” - > “章名” - > “子章名”。

“章节”下面的层次需要动态添加。当我这样做时,菜单在尝试显示章节名称的子项时会消失。

如果您运行下面的代码示例,您可以单击“转到”和“章节”,但只要将鼠标悬停在其中一个章节名称上,菜单就会消失而不允许其中一个子章节名称点击。

谁能告诉我为什么?

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

1 个答案:

答案 0 :(得分:1)

为GotoMenu下面的每个菜单级别调用OnSubMenuOpen,因此每次展开都会清除ChapterMenu。

在OnSubMenuOpen的第一行,检查来自哪里的电话:

 void OnSubMenuOpen(object Sender, RoutedEventArgs e)
 {
    if (e.Source != GotoMenu) return;