WPF 关于在ContextMenu中绑定带参数的命令

Come From
https://www.cnblogs.com/muran/p/6702444.html
https://stackoverflow.com/questions/504533/commandparameters-in-contextmenu-in-wpf

问题,Button上挂了一个ContextMenu,绑定命令参数的时候如何传递父级或者更高级的元素进去。
由于:ContextMenu无论定义在.cs或.xaml文件中,都不继承父级的DataContext,所以如果要绑定父级的DataContext,直接DataContext=“{Binding}”是行不通的

如果想传递附着的元素Button
CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}, Path=PlacementTarget}"

如果你想传递Button的父级元素
CommandParameter="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}"

原文地址:https://www.cnblogs.com/swobble/p/12859202.html