首页 > 解决方案 > ContextMenu 绑定菜单项标题 MVVM

问题描述

我是 WPF 新手,我想将上下文菜单标题和命令绑定到视图模型中的集合。SO上有很多类似的问题。但没有人帮助我。

虚拟机:

    private ObservableCollection<ContextAction> _items;

    public ObservableCollection<ContextAction> Items
    {
        get { return _items; }
        set { _items = value; RaisePropertyChanged(nameof(Items)); }
    }

ContextAction

public class ContextAction
{
    public string Name;
    public ICommand Action;
}

Items收藏:

    Items = new ObservableCollection<ContextAction>(
            new List<ContextAction>
            {
                new ContextAction
                {
                    Action = new DelegateCommand(Command),
                    Name = "Item1"
                },

                new ContextAction
                {
                    Action = new DelegateCommand(Command),
                    Name = "Item2"
                }
            });

我试过了:

<Button Content="2" Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}}">
  <Button.ContextMenu>
   <ContextMenu DataContext="{Binding Path=PlacementTarget.Tag,
        RelativeSource={RelativeSource Self}}">
     <MenuItem Command="{Binding PlacementTarget.Tag.Items.Action, 
        RelativeSource={RelativeSource Mode=FindAncestor,
        AncestorType={x:Type ContextMenu}}}"
        Header="{Binding PlacementTarget.Tag.Items.Name}" />
    </ContextMenu>
  </Button.ContextMenu>
</Button>

标签: wpfxaml

解决方案


推荐阅读