In the MVVM pattern, use the ICommand command to bind the event with the following code:
ViewModel definition command: Public ICommand Removecommand {get; private set;}, constructor Initialization command: Removecommand=new Relaycommand ( Remove,canexecute);
The following is the definition of Relaycommand.
public class Relaycommand:icommand
{
#region Fields&constructors
Private ReadOnly action<object> _execute;
Private ReadOnly predicate<object> _canexecute;
Public Relaycommand (action<object> execute)
: This (execute, NULL)
{
}
Public Relaycommand (action<object> Execute, predicate<object> canexecute)
{
if (execute = = null)
throw new ArgumentNullException ("execute");
_execute = Execute;
_canexecute = CanExecute;
}
#endregion
#region Icommand Members
public void Execute (object parameter)
{
if (parameter==null)
//{
Return
//}
if (! CanExecute (parameter))
{
throw new InvalidOperationException ("The command is not valid for execution, check the CanExecute method before attempting To execute. ");
}
_execute (parameter);
}
public bool CanExecute (object parameter)
{
return _canexecute = = NULL | | _canexecute (parameter);
}
Public event EventHandler Canexecutechanged
{
Add {commandmanager.requerysuggested + = value;}
Remove {commandmanager.requerysuggested-= value;}
}
#endregion
View is the command for the right-click menu binding:
<DataGrid.ContextMenu>
<ContextMenu>
<menuitem header= "Delete" command= "{Binding Removecommand}" inputgesturetext= "delete"/>
</ContextMenu>
</DataGrid.ContextMenu>
The above code in the Win7 flagship system, XP system and WIN8 system are operating normally, except Win7 Professional version run do not delete function, in CanExecute that return false, right-click menu dimmed, but Win7 Professional version installed vs after the good, But not every user to install the software when the VS Ah, feeling that some components are not complete or low-level components, do not know why.
Later, the solution is to use public static Routeduicommand Removecommand = new Routeduicommand () in View.cs, and define the command
private void Commandbinding_oncanexecute (object sender, Canexecuteroutedeventargs e)
{
Interpretation criteria whether the Delete command is executed
}
private void Commandbinding_onexecuted (object sender, Executedroutedeventargs e)
{
Execute Delete command
}
In view: First add this:
<UserControl.CommandBindings>
<commandbinding command= "View:AnimationEditor.RemoveCommand" canexecute= "Commandbinding_oncanexecute" Executed = "Commandbinding_onexecuted" ></CommandBinding>
</UserControl.CommandBindings>
Then in the right-click menu:
<DataGrid.ContextMenu>
<ContextMenu>
<menuitem header= "Delete" command= "View:Editor.RemoveCommand" inputgesturetext= "Delete"/>
</ContextMenu>
</DataGrid.ContextMenu>
So modified in any system is no problem, but I still do not know the specific reasons, please expert advice.
Win7 Pro System Event-bound command event does not execute