This is an auxiliary class of events that can be used to implement the MenuItem command event
Public classmycommands:freezable, ICommand, ICommandSource { Publicmycommands () {} Public Static ReadOnlyDependencyProperty Commandparameterproperty =Dependencyproperty.register ("CommandParameter", typeof(Object), typeof(mycommands),NewPropertyMetadata ((Object)NULL)); Public ObjectCommandParameter {Get { return(Object) GetValue (Commandparameterproperty); } Set{SetValue (commandparameterproperty, value); } } Public Static ReadOnlyDependencyProperty Commandtargetproperty =Dependencyproperty.register ("Commandtarget", typeof(IInputElement),typeof(mycommands),NewPropertyMetadata ((IInputElement)NULL)); Publiciinputelement Commandtarget {Get { return(IInputElement) GetValue (Commandtargetproperty); } Set{SetValue (commandtargetproperty, value); } } Public Static ReadOnlyDependencyProperty Commandproperty = Dependencyproperty.register ("Command",typeof(ICommand),typeof(Mycommands),NewPropertyMetadata (NewPropertychangedcallback (oncommandchanged)); PublicICommand Command {Get{return(ICommand) GetValue (commandproperty);} Set{SetValue (commandproperty, value);} } #regionICommand Members Public BOOLCanExecute (Objectparameter) { if(Command! =NULL) returnCommand.canexecute (CommandParameter); return false; } Public voidExecute (Objectparameter) {Command.Execute (CommandParameter); } Public EventEventHandler canexecutechanged; Private Static voidoncommandchanged (DependencyObject D, DependencyPropertyChangedEventArgs e) {mycommands Commandrefe Rence= d asMycommands; ICommand Oldcommand= E.oldvalue asICommand; ICommand Newcommand= E.newvalue asICommand; if(Oldcommand! =NULL) {oldcommand.canexecutechanged-=commandreference.canexecutechanged; } if(Newcommand! =NULL) {newcommand.canexecutechanged+=commandreference.canexecutechanged; } } #endregion #regionFreezableprotected OverrideFreezable Createinstancecore () {Throw Newnotimplementedexception (); } #endregion }
Methods that are called in XAML
<UserControl.Resources> <unititys:mycommands x:key="AAA"Command="{Binding PATH=AAA}"/></usercontrol.resources> <contextmenu x:key="RouterMenu1"datacontext="{Binding Relativesource={relativesource mode=self}, Path=placementtarget.datacontext}"> <menuitem header="Call AAA"Command="{StaticResource AAA}"></MenuItem> </ContextMenu>
In ViewModel and normal command-like calls.
Command event for WPF MVVM MenuItem