【问题标题】:Passing the control as CommandParameter programmatically以编程方式将控件作为 CommandParameter 传递
【发布时间】:2016-04-10 09:51:00
【问题描述】:

当试图传递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 传递。

我错过了什么?

【问题讨论】:

  • 语法是XAML markup extension,不能在C#代码中使用。查找父元素,可以在代码中使用VisualTreeHelper
  • 在 ViewModel 中使用 VisualTreeHelper 违反了 MVVM 模式,就像使用 MenuItem 一样。两者分别在 PresentationCore.dll 和 Presentation.dll 中定义

标签: c# wpf mvvm command commandparameter


【解决方案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);
    }
}

【讨论】:

  • 在 ViewModel 中使用视图类型违反了 MVVM 模式
猜你喜欢
  • 1970-01-01
  • 2014-04-22
  • 1970-01-01
  • 2012-09-04
  • 1970-01-01
  • 1970-01-01
  • 2015-11-05
  • 2014-06-13
  • 2012-08-01
相关资源
最近更新 更多