C# Class CK.WPF.Controls.SimpleCommand

A command whose sole purpose is to relay its functionality to other objects by invoking delegates. The default return value for the CanExecute method is 'true'. From http://mvvmfoundation.codeplex.com/ open source project.
CanExecuteChanged and memory leaks.

This class uses the centralized CommandManager.RequerySuggested to implement CanExecuteChanged event when a CanExecute delegate is provided.

Apparently, WPF expects this event to be implemented as a weak event. That means, the event should use a List<WeakReference> for the delegates, so that objects don’t have to unregister (because they don’t!).

Interestingly, this means a WeakReference to the delegate, not to the listening object – the listening object must keep a reference to its own delegate instance so that the delegate doesn’t get garbage collected even though the listening object is still reachable. CommandManager.RequerySuggested is such a weak event, so code below works fine.

The default interface implementation generated by VS – a default C# event (“public EventHandler CanExecuteChanged;”) – will cause a memory leak! So basically, there are only two easy options: If CanExecute never changes and you don’t intend to fire the event, then don’t use a default event, use an event that doesn’t store the delegates. public event EventHandler CanExecuteChanged { add { } remove { } } 2) If CanExecute changes, use the CommandManager.
Inheritance: ICommand
Show file Open project: Invenietis/ck-certified

Public Methods

Method Description
Execute ( object parameter ) : void
SimpleCommand ( System.Action execute ) : System

Creates a new command that can always execute.

SimpleCommand ( System.Action execute, Func canExecute ) : System

Creates a new command.

Private Methods

Method Description
CanExecute ( object parameter ) : bool

Method Details

Execute() public method

public Execute ( object parameter ) : void
parameter object
return void

SimpleCommand() public method

Creates a new command that can always execute.
public SimpleCommand ( System.Action execute ) : System
execute System.Action The execution logic.
return System

SimpleCommand() public method

Creates a new command.
public SimpleCommand ( System.Action execute, Func canExecute ) : System
execute System.Action The execution logic.
canExecute Func The execution status logic.
return System