Observable Collection中的上下文菜单命令

时间:2013-11-16 18:55:43

标签: wpf mvvm binding contextmenu

我是WPF的新手,我正在尝试将上下文菜单绑定到模型的ObservableCollection。我能够显示上下文菜单,但我无法触发命令。这是我的代码

<ContextMenu ItemsSource="{Binding ContextMenuList}">
  <ContextMenu.ItemContainerStyle>
    <Style TargetType="{x:Type MenuItem}">
      <Setter Property="MenuItem.Header" Value="{Binding Name}" />
      <Setter Property="MenuItem.ItemsSource" Value ="{Binding Children}" />
      <Setter Property="Command" Value="{Binding MenuCommand}"/>
    </Style>
  </ContextMenu.ItemContainerStyle>
</ContextMenu>

在视图模型中我有


    public class MenuItemViewModel
    {
        public string Name { get; set; }
        public ObservableCollection Children { get; set; }
        public ICommand MenuCommand;

        public MenuItemViewModel(string name, ObservableCollection pChildren, ICommand pCommand)
        {
            this.Name = name;
            this.Children = pChildren;
            this.MenuCommand = pCommand;
        }
    }

我填充了这个集合

public void AddContextMenuItems()
{
        this.ContextMenuList = new ObservableCollection<MenuItemViewModel>();

        ICommand pCommand = new ActionCommand(() => this.ChangeChartType());
        MenuItemViewModel ohlc = new MenuItemViewModel("OHLC",null,pCommand);

        MenuItemViewModel candlestick = new MenuItemViewModel("CandleStick");
        ObservableCollection<MenuItemViewModel> chartTypeColl = new ObservableCollection<MenuItemViewModel>();
        chartTypeColl.Add(ohlc);
        chartTypeColl.Add(candlestick);

        this.ContextMenuList.Add(new MenuItemViewModel("ChartType",chartTypeColl));
}

我没有看到ChangeChartType方法被触发,我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

尝试将MenuCommand字段更改为属性

public ICommand MenuCommand { get; set; }

希望这对你有用。我没有试过这个。