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>
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 Solution to command cannot be bound in MVVM mode