I am trying to implement ICommandSource on a custom control (similar to a button). Currently the implementation is mostly like it is displayed on the msdn page for ICommandSource and as it shows in the ButtonBase source code.
CanExecute fires on load of the control but doesn’t fire when any property has changed. The same command being passed to a regular button works just fine. When the property that is supposed to change changes, CanExecute fires and the button is enabled. The command is a Delegate Command.
I have tried CommandManager.InvalidateRequerySuggested(); but that has not worked.
Any ideas?
Here’s the implementation in the custom control:
private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CollapsibleSplitButton csb = (CollapsibleSplitButton)d;
csb.OnCommandChanged((ICommand)e.OldValue, (ICommand)e.NewValue);
}
private void OnCommandChanged(ICommand oldCommand, ICommand newCommand)
{
if (oldCommand != null) UnhookCommand(oldCommand);
if (newCommand != null) HookCommand(newCommand);
}
private void UnhookCommand(ICommand command)
{
command.CanExecuteChanged -= OnCanExecuteChanged;
UpdateCanExecute();
}
private void HookCommand(ICommand command)
{
command.CanExecuteChanged += OnCanExecuteChanged;
UpdateCanExecute();
}
private void OnCanExecuteChanged(object sender, EventArgs e)
{
UpdateCanExecute();
}
private void UpdateCanExecute()
{
if (Command != null)
CanExecute = Command.CanExecute(CommandParameter);
else
CanExecute = true;
}
protected override bool IsEnabledCore
{
get { return base.IsEnabledCore && CanExecute; }
}
Where I setup the Command I have:
...
MyCommand = new DelegatingCommand(DoStuff, CanDoStuff);
...
private bool CanDoStuff()
{
return (DueDate == null);
}
private void DoStuff() {//do stuff}
Managed to resolve the issue by wrapping the callback in an EventHandler.