0

I'm trying to create a nested menu hierarchy from the main menu bar. For example, the main menu bar would contain a "Goto" menuitem that could be navigated as "Goto" -> "Chapter" -> "Chapter Name" -> "Subchapter name".

The hierachy below "Chapter" needs to be added dynamically. When I do this, the menu disappears when it tries to display the subitems of a chapter name.

If you run the code sample below, you can click on "Goto" and "Chapter", but as soon as you hover over or click on one of the chapter names, the menus disappear without allowing one of the subsection names to be clicked.

Can anyone tell me why?

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

1 回答 1

1

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

在 OnSubMenuOpen 的第一行,检查调用的来源:

 void OnSubMenuOpen(object Sender, RoutedEventArgs e)
 {
    if (e.Source != GotoMenu) return;
于 2009-11-26T21:21:58.103 回答