0

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?

4

1 回答 1

1

您可以使用下面提到的代码来实现

你的 xml 代码看起来像

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

你的 ViewModel 看起来像

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);
    }
}
于 2016-01-06T11:02:51.320 回答