以编程方式将控件作为CommandParameter传递

时间:2016-01-06 10:30:52

标签: c# wpf mvvm command commandparameter

尝试在xaml中传递控件时,我们编写以下代码:

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

我尝试以编程方式创建MenuItem,如下所示:

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

这会将string "{Binding RelativeSource= {RelativeSource Mode=FindAncestor, AncestorType={x:Type MenuItem}}}"作为CommandParameter传递。

我错过了什么?

1 个答案:

答案 0 :(得分:1)

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

来实现

你的xaml代码看起来像

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