Home > Software engineering >  Dynamic menu items with dynamic shortcut keys using c# wpf
Dynamic menu items with dynamic shortcut keys using c# wpf

Time:11-17

My question about c# wpf

I am creating one windows application using c# WPF, I am creating menus on main window using menu control from code behind (c#) menu's data coming from database. One more table in my database for keyboard short cut key data. So, I want to assign that short cut key value in respective menu item. How can we achieve that?

In short how to assign dynamic short cut key values to dynamic menu items?

For example, Menu is _Transactions Menu Item is _Sales Sub Menu Item is _Add Sub Menu Item is _Display

Short Cut key data from database KeyValue for Transaction Menu is Alt T

Sample code is...

try
        {
            menuContainer.Children.Clear();
            System.Windows.Controls.Menu topMenu = new 
System.Windows.Controls.Menu();
            DataTable dtMainMenu = Global.DatabaseMethod.GetMenuData();
            DataTable dtSubMenu = null;
            DataTable dtChildMenu = null;
            DataTable dtSubChildMenu = null;
            if (dtMainMenu != null && dtMainMenu.Rows.Count > 0)
            {
                MenuItem parentMenuItem = null;
                MenuItem subMenuItem = null;
                MenuItem childMenuItem = null;
                MenuItem subchildMenuItem = null;
                DataRow[] dataRow = null;
                dtMainMenu.DefaultView.Sort = "SequenceNumber ASC";
                dtMainMenu = dtMainMenu.DefaultView.ToTable();
                foreach (DataRow parentMenuRow in dtMainMenu.Rows)
                {
                    parentMenuItem = new MenuItem();
                    parentMenuItem.Tag = 
parentMenuRow[ColumnNameConstants.Slug].ToString()   "~"   
parentMenuRow[ColumnNameConstants.ID].ToString();
                    parentMenuItem.Header = 
parentMenuRow[ColumnNameConstants.MenuName].ToString();
                    dataRow = Global.dtUserRole.Select("((MenuId='"   
Convert.ToInt32(parentMenuRow[ColumnNameConstants.ID])   "' AND 
SubMenuId=0 AND ChildMenuId=0) OR (MenuId='"   
Convert.ToInt32(parentMenuRow[ColumnNameConstants.ID])   "'))");
                    parentMenuItem.PreviewMouseDown  = 
MenuItem_PreviewMouseDown;
                    parentMenuItem.PreviewKeyDown  = 
MenuItem_PreviewKeyDown;
                    if (dataRow.Length > 0)
                    {
                        topMenu.Items.Add(parentMenuItem);
                        if (!Convert.ToBoolean(dataRow[dataRow.Length - 
1][ColumnNameConstants.VisibleRole]))
                        {
                            parentMenuItem.Visibility = 
Visibility.Collapsed;
                        }
                    }
                    else
                    {
                        topMenu.Items.Add(parentMenuItem);
                        parentMenuItem.Visibility = 
Visibility.Collapsed;
                    }
                }
                topMenu.Background = Brushes.Transparent;
                topMenu.Foreground = Brushes.White;
                topMenu.VerticalAlignment = VerticalAlignment.Center;
                menuContainer.Children.Add(topMenu);
            }
        }
        catch (Exception ex)
        {
         
        }

CodePudding user response:

This should get you a bit closer.

    <Window x:Class="WpfApp11.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfApp11"
            mc:Ignorable="d"
            Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
        <Grid>
            <Menu x:Name="mainmenu" VerticalAlignment="Top"/>
        </Grid>
    </Window>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp11
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, ICommand
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            MenuItem filemenu = new MenuItem();
            filemenu.Header = "_File";

            MenuItem menuitem1 = new MenuItem();
            menuitem1.Header = "Item _1";
            menuitem1.InputGestureText = "Ctrl A";
            //menuitem1.Click  = menuitem_Click;
            //menuitem1.Tag = "slug1~id1"; //parentMenuRow[ColumnNameConstants.Slug].ToString()   "~"   parentMenuRow[ColumnNameConstants.ID].ToString();
            menuitem1.CommandParameter = "slug1~id1"; //parentMenuRow[ColumnNameConstants.Slug].ToString()   "~"   parentMenuRow[ColumnNameConstants.ID].ToString();
            menuitem1.Command = this;

            MenuItem menuitem2 = new MenuItem();
            menuitem2.Header = "Item _2";
            menuitem2.InputGestureText = "Ctrl B";
            //menuitem2.Click  = menuitem_Click;
            //menuitem2.Tag = "slug2~id2"; //parentMenuRow[ColumnNameConstants.Slug].ToString()   "~"   parentMenuRow[ColumnNameConstants.ID].ToString();
            menuitem2.CommandParameter = "slug2~id2"; //parentMenuRow[ColumnNameConstants.Slug].ToString()   "~"   parentMenuRow[ColumnNameConstants.ID].ToString();
            menuitem2.Command = this;

            filemenu.Items.Add(menuitem1);
            filemenu.Items.Add(menuitem2);

            mainmenu.Items.Add(filemenu);

            this.InputBindings.Add(new KeyBinding(this, Key.A, ModifierKeys.Control) { Command = this, CommandParameter = "slug1~id1" });
            this.InputBindings.Add(new KeyBinding(this, Key.B, ModifierKeys.Control) { Command = this, CommandParameter = "slug2~id2" });
        }

        //----------------------------------------------------------------------

        private void menuitem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem menu = sender as MenuItem;

            if (menu != null)
            { 
                MessageBox.Show(menu.Tag as string);

                e.Handled = true;
            }
        }

        //----------------------------------------------------------------------

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested  = value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public bool CanExecute(object parameter)
        {
            string item = parameter as string;

            if (item == "slug1~id1")
            { 
                // Decide if command should be enabled of not

                return true;
            }

            if (item == "slug2~id2")
            {
                // Decide if command should be enabled of not

                return true;
            }

            return false;
        }

        public void Execute(object parameter)
        {
            ExecuteItem(parameter);
        }

        //----------------------------------------------------------------------

        private void ExecuteItem(object parameter)
        {
            string item = parameter as string;

            if (item != null)
            {
                MessageBox.Show(item);
            }
        }
    }
}
  • Related