我是WPF的新手,我想将上下文菜单标题和命令绑定到视图模型中的集合。关于SO有许多类似的问题。但是没有人帮助我。
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
集合:
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>