I would like to call an ApplicationCommand with a MenuItem-Click:
<MenuItem Header="{StaticResource MenuItemSave}" Command="ApplicationCommands.Save"/>
In my ViewModel-Constructor I inizialize my bindings with:
CommandBinding saveBinding = new CommandBinding(ApplicationCommands.Save, SaveCommand_Execute, SaveCommand_CanExecute);
CommandManager.RegisterClassCommandBinding(typeof(ViewModel_Main), saveBinding);
RegisterCommandBindings.Add(saveBinding);
Now I would like to handle the command, but it simply is not executeable. Even if it should be ALWAYS true.
private void SaveCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void SaveCommand_Execute(object sender, ExecutedRoutedEventArgs e)
{
//Stuff
}
I have also tried to update all bindings after my init function:
CommandManager.InvalidateRequerySuggested();
But my MenuItem stays disabled.
Thank you!
I would suggest using this implementation of ICommand
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
namespace Common
{
public class Command<TArgs> : ICommand
{
public Command(Action<TArgs> exDelegate)
{
_exDelegate = exDelegate;
}
public Command(Action<TArgs> exDelegate, Func<TArgs, bool> canDelegate)
{
_exDelegate = exDelegate;
_canDelegate = canDelegate;
}
protected Action<TArgs> _exDelegate;
protected Func<TArgs, bool> _canDelegate;
#region ICommand Members
public bool CanExecute(TArgs parameter)
{
if (_canDelegate == null)
return true;
return _canDelegate(parameter);
}
public void Execute(TArgs parameter)
{
if (_exDelegate != null)
{
_exDelegate(parameter);
}
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
bool ICommand.CanExecute(object parameter)
{
if (parameter != null)
{
var parameterType = parameter.GetType();
if (parameterType.FullName.Equals("MS.Internal.NamedObject"))
return false;
}
return CanExecute((TArgs)parameter);
}
void ICommand.Execute(object parameter)
{
Execute((TArgs)parameter);
}
#endregion
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.