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>