0

I'm new to WPF and I want to bind context menu header and command to a collection in a view model. There are many similar questions on SO. But none helped me.

VM:

    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 Collection:

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

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

And I tried:

<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>
John D.
  • 37
  • 7
  • Possible duplicate of [WPF: Binding a ContextMenu to an MVVM Command](https://stackoverflow.com/questions/3583507/wpf-binding-a-contextmenu-to-an-mvvm-command) – Mark Feldman Jan 28 '19 at 19:53
  • @MarkFeldman I tried that too. Can you tell me where my mistake is? – John D. Jan 29 '19 at 11:59
  • You need to use the BindingProxy. Context menus aren't part of the main visual tree, so data binding doesn't work the way it normally does and you have to instead use a proxy. If you try implementing the proxy and it still doesn't work then post your code here and I'll remove the duplicate flag and post an answer. Good luck! – Mark Feldman Jan 29 '19 at 12:01

0 Answers0