Search code examples
c#wpfmvvmcommandcommandparameter

Passing the control as CommandParameter programmatically


When trying to pass the control in xaml, we write the following code:

<MenuItem x:Name="NewMenuItem" Command="{Binding MenuItemCommand}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MenuItem}}}" />

I'm trying to create a MenuItem programmatically, like this:

var pluginMenuItem = new MenuItem
{
    Header = "NewMenuItem, 
    Command = MenuItemCommand,
    CommandParameter = "{Binding RelativeSource= {RelativeSource Mode=FindAncestor, AncestorType={x:Type MenuItem}}}"
};

This passes the string "{Binding RelativeSource= {RelativeSource Mode=FindAncestor, AncestorType={x:Type MenuItem}}}" as the CommandParameter.

What am I missing?


Solution

  • You can achieve thing using below mentioned code

    your xaml code look like

     <Menu Name="menu" ItemsSource="{Binding MenuList,Mode=TwoWay}">
      </Menu>
    

    Your ViewModel look like

    public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            MenuList.Add(new MenuItem()
            {
                Header = "MenuItem1",
                Command = MenuItemCommand,
                CommandParameter = "FirstMenu"
            });
            MenuList.Add(new MenuItem()
            {
                Header = "MenuItem2",
                Command = MenuItemCommand,
                CommandParameter = "SecondMenu"
            });
        }
    
        private ObservableCollection<MenuItem> _menuList;
    
        public ObservableCollection<MenuItem> MenuList
        {
            get { return _menuList ?? (_menuList = new ObservableCollection<MenuItem>()); }
            set { _menuList = value; RaisePropertyChanged("MenuList"); }
        }
    
        private RelayCommand<string> _MenuItemCommand;
    
        public RelayCommand<string> MenuItemCommand
        {
            get { return _MenuItemCommand ?? (_MenuItemCommand = new RelayCommand<string>(cmd)); }
            set { _MenuItemCommand = value; }
        }
    
        private void cmd(string value)
        {
            MessageBox.Show(value);
        }
    }