Original: WPF ContextMenu bind command in MVVM mode and use CommandParameter to pass arguments
ContextMenu regardless of whether it is defined in a. cs or. xaml file, the parent's DataContext is not inherited, so if you want to bind the DataContext of the parent, the direct datacontext= "{Binding}" is not feasible
Cannot bind parent, but can bind resources
First step: Define an intermediate class to use as a resource object
1 Public classbindingproxy:freezable2 {3 #regionOverrides of Freezable4 5 protected OverrideFreezable Createinstancecore ()6 {7 return Newbindingproxy ();8 }9 Ten #endregion One A Public ObjectData - { - Get{return(Object) GetValue (Dataproperty); } the Set{SetValue (dataproperty, value);} - } - - Public Static ReadOnlyDependencyProperty Dataproperty = +Dependencyproperty.register ("Data",typeof(Object),typeof(Bindingproxy),NewUIPropertyMetadata (NULL)); -}
Step two: Referencing namespaces, defining resources in controls
1 <UserControl.Resources>2 <libbinding:bindingproxy x:key=" Bindingproxy" data="{Binding}"/>3 </ Usercontrol.resources>
Step three: Bind ContextMenu, MenuItem
(The bindings for Button.command and Contextmenu.isopen can be a concern, and these two bindings are used to control the ContextMenu open)
1<button command="{Binding Customfold}">2<Button.ContextMenu>3<contextmenu datacontext="{Binding Data,source={staticresource bindingproxy}}" 4Itemssource="{Binding Itemmodelcollection}"5isopen="{Binding Opencustomfold,mode=oneway}">6<ContextMenu.ItemContainerStyle>7<style targettype="MenuItem">8<setter property="Header"Value="{Binding ...}"/>9<setter property="Command"Value="{Binding ...}"/>Ten<setter property="CommandParameter"Value="{Binding ...}"/> One</Style> A</ContextMenu.ItemContainerStyle> -</ContextMenu> -</Button.ContextMenu> the<image .../> -</Button>
Fourth step: Passing Parameters
ContextMenu is the root node of its own visual tree, so the parameters to be passed are not found even through relativesource.findancestor.
Resolution: Can be resolved by Placementtarget. Microsoft's explanation for Placementtarget is: Gets or sets the UIElement when it is opened relative to the location of the ContextMenu. It should be understood as the UIElement to place this contextmenu.
1 commandparameter="{Binding Relativesource={relativesource mode=findancestor, Ancestortype=contextmenu}, Path=placementtarget}"
If you want to pass item, such as the SelectedItem of the listbox:
1 commandparameter="{Binding Relativesource={relativesource mode=findancestor, Ancestortype=contextmenu}, Path=placementtarget.selecteditem}"
Reference:
http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/
Http://stackoverflow.com/questions/1580753/wpf-contextmenu-with-itemssource-how-to-bind-to-command-in-each-item
WPF ContextMenu bind command in MVVM mode and use CommandParameter to pass parameters