Best way to handle MenuItem Click events?

I am wondering how best to handle 30 or so. Click events for MenuItems?

My first thought was to simply create an event listener for each MenuItem as follows:

XAML:

<Menu Name="MainMenu" IsMainMenu="True" Height="25">
        <MenuItem Header="_File" >
            <MenuItem Name="New" Header="_New" Click="MenuItem_NewClick" />
            <MenuItem Name="Open" Header="_Open" Click="MenuItem_OpenClick" />
            <MenuItem Name="Save" Header="_Save" Click="MenuItem_SaveClick" />
        </MenuItem>
</Menu>

C # 1:

private void MenuItem_NewClick(object sender, RoutedEventArgs e)
{           
    //Do work...
}
private void MenuItem_OpenClick(object sender, RoutedEventArgs e)
{
    //Do work...
}
private void MenuItem_SaveClick(object sender, RoutedEventArgs e)
{
    //Do work...
}

But this seems dirty, especially for MenuItems, which does not require a lot of code, such as Copy or Paste.

Instead, I could use a single event listener and use if / case to check the MenuItem and exclude all additional event listeners as follows:

C # 2:

private void MenuItem_FileClick(object sender, RoutedEventArgs e)
    {
        MenuItem item = e.OriginalSource as MenuItem;
        switch (item.Name)
        {
            case "New":
                MessageBox.Show("New File Created.");
                break;
            case "Open":
                MessageBox.Show("File Opened Created.");
                break;
            case "Save":
                MessageBox.Show("File Saved.");
                break;
        }
    }

, , MenuItems , . , , , ?

?

,

+4
1

, , .

        var actions = new Dictionary<string, Func<MenuItem, RoutedEventHandler>>()
        {
            { "New", mi => (s, e) => { MessageBox.Show("New File Created."); }},
            { "Open", mi => (s, e) => { MessageBox.Show("File Opened."); }},
            { "Save", mi => (s, e) => { MessageBox.Show("File Saved."); }},
        };

        foreach (MenuItem mi in FileMenu.Items)
        {
            if (actions.ContainsKey(mi.Name))
            {
                mi.Click += actions[mi.Name](mi);
            }
        }

, mnu . , , :

            {
                "New",
                mi =>
                    (s, e) =>
                    {
                        MessageBox.Show("New File Created.");
                        MessageBox.Show(
                            String.Format("You clicked the {0} menu.", mi.Name));
                    }
            },

, mi .

, , , . , , , , .

+2

All Articles