Performance penalty of continuous CanExecute calls in Command - wpf

I am applying the MVVM pattern to a project. I have a UserControl that has a button which is bound to a command exposed by the ViewModel.
Since the button is visible, it's calling continuously the CanExecute method of the button. Something tells me that this carries a performance penalty, but I'm not sure. Is this the expected behavior? or is there a better way of having a button bound to a command?
Thank you.

Sorry, I found out what was happening.
This is the implementation of RelayCommand.
public class RelayCommand : ICommand
{
#region Fields
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
#endregion // Fields
#region Constructors
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 // Constructors
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
#endregion // ICommand Members
}
I had incorrectly assumed the system was requerying ALL commands automatically. What it actually does is hook to each Command's CanExecuteChanged event, and RelayCommand basically links its CanExecuteChanged event to the CommandManager's RequerySuggested event, so each time the system "suggests" a requery, it was in fact requerying all my RelayCommands.
Thank you.

Related

Button stays disabled - DelegateCommand not re-evaluating CanExecute handler

Problem: Buttons never gets enabled.
<Button Name="btnCompareAxises"Command="{Binding CompareCommand}"
Content="{Binding VM.CompareAxisButtonLabel}"
IsEnabled="{Binding VM.IsCompareButtonEnabled}">
</Button>
ViewModel constructor:
this.CompareCommand = new DelegateCommand(CompareCommand, ValidateCompareCommand);
The problem seems to be related to the CanExecute eventhandler of the registered Command of the button.
The CanExecute handler returns false when the application loads.
This is fine, as the conditions are not met initially.
The canExecute handler only runs on application startup or when the button is clicked. You cannot click a disabled button, so the button stays disabled forever if the initial value returned form the CanExecute handler is false!
Question:
Do I have to enable the button again, only using the command bound to it.
Something like, hey command please reevaluate if the conditions for this buttons are met ?
Why sits the IsEnabled property under section Coercion and not under local?
The command:
public class DelegateCommand : ICommand
{
private readonly Func<object, bool> canExecute;
private readonly Action<object> execute;
public DelegateCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
this.execute = execute;
this.canExecute = canExecute;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return this.canExecute == null || this.canExecute(parameter);
}
public void Execute(object parameter)
{
this.execute(parameter);
}
public void RaiseCanExecuteChanged()
{
this.OnCanExecuteChanged();
}
protected virtual void OnCanExecuteChanged()
{
var handler = this.CanExecuteChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
Solved:
I had to adapt the DelegateCommand class to make it work:
I have added CommandManager.RequerySuggested to the public CanExecuteChanged Event property.
Now it will automatically re-evaluate the CanExecute method of the command when soemthing changes in the UI!
public class DelegateCommand : ICommand
{
private readonly Func<object, bool> canExecute;
private readonly Action<object> execute;
public DelegateCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
this.execute = execute;
this.canExecute = canExecute;
}
/// CommandManager
/// Go to the "References" part of your class library and select "Add Reference".
/// Look for an assembly called "PresentationCore" and add it.
public event EventHandler CanExecuteChanged
{
add
{
_internalCanExecuteChanged += value;
CommandManager.RequerySuggested += value;
}
remove
{
_internalCanExecuteChanged -= value;
CommandManager.RequerySuggested -= value;
}
}
event EventHandler _internalCanExecuteChanged;
public bool CanExecute(object parameter)
{
return this.canExecute == null || this.canExecute(parameter);
}
public void Execute(object parameter)
{
this.execute(parameter);
}
public void RaiseCanExecuteChanged()
{
this.OnCanExecuteChanged();
}
protected virtual void OnCanExecuteChanged()
{
var handler = this._internalCanExecuteChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
Removed this from the button:
IsEnabled="{Binding VM.IsCompareButtonEnabled}"
The binding here is not necessary, as the CanExecute handler will take care of the enabled/disabled state of the button!

RelayCommand Memory leak

I am looking for an implementation of RelayCommand. The original implementation that I considered was the classic one (lets call it implementation A)
public class RelayCommand : ICommand
{
private readonly Predicate<object> canExecute;
private readonly Action<object> execute;
private EventHandler canExecuteEventhandler;
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}
this.execute = execute;
this.canExecute = canExecute;
}
public event EventHandler CanExecuteChanged
{
add
{
this.canExecuteEventhandler += value;
}
remove
{
this.canExecuteEventhandler -= value;
}
}
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return this.canExecute == null ? true : this.canExecute(parameter);
}
[DebuggerStepThrough]
public void Execute(object parameter)
{
this.execute(parameter);
}
public void InvokeCanExecuteChanged()
{
if (this.canExecute != null)
{
if (this.canExecuteEventhandler != null)
{
this.canExecuteEventhandler(this, EventArgs.Empty);
}
}
}
}
This is the implementation that I have used since I started developing in Silverlight around 2009. I have also used it in WPF applications.
Lately I understood that it has a memory leak problem in cases where the views that bind to the command have shorter life span than the command itself. Apparently when a button binds to the command, it of course registers to the CanExecuteChanged event handler but never unregistered. The default event handlers hold strong reference to the delegate, which holds a strong reference to the button itself, therefore the RelayCommand keeps the button alive and that's a memory leak.
Another implementation that I have found uses the CommandManager. The CommandManager exposes a a RequerySuggested event and internally only hold weak references to the delegates. So the definition of the event can be implemented as follows (implementation B)
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void RaiseCanExecuteChanged()
{
CommandManager.InvalidateRequerySuggested();
}
So that every delegate is passed to the static event handler instead of being held by the relay command itself. My problem with this implementation is that it relies on the CommandManager to know when to raise the event. Also, when RaiseCanExecuteChanged is called, the command manager raises this event for all RelayCommands, not specifically the one that initiated the event.
The last implementation I found was from MvvmLight where the event is defined as such (implementation C):
public event EventHandler CanExecuteChanged
{
add
{
if (_canExecute != null)
{
// add event handler to local handler backing field in a thread safe manner
EventHandler handler2;
EventHandler canExecuteChanged = _requerySuggestedLocal;
do
{
handler2 = canExecuteChanged;
EventHandler handler3 = (EventHandler)Delegate.Combine(handler2, value);
canExecuteChanged = System.Threading.Interlocked.CompareExchange<EventHandler>(
ref _requerySuggestedLocal,
handler3,
handler2);
}
while (canExecuteChanged != handler2);
CommandManager.RequerySuggested += value;
}
}
remove
{
if (_canExecute != null)
{
// removes an event handler from local backing field in a thread safe manner
EventHandler handler2;
EventHandler canExecuteChanged = this._requerySuggestedLocal;
do
{
handler2 = canExecuteChanged;
EventHandler handler3 = (EventHandler)Delegate.Remove(handler2, value);
canExecuteChanged = System.Threading.Interlocked.CompareExchange<EventHandler>(
ref this._requerySuggestedLocal,
handler3,
handler2);
}
while (canExecuteChanged != handler2);
CommandManager.RequerySuggested -= value;
}
}
}
So in addition to the command manager it also holds the delegate locally and does some magic trick to support thread safety.
My questions are:
Which of these implementations actually solve the memory leak problem.
Is there an implementation that solves the problem without relying on the CommandManager?
Is the trick that is done in implementation C really necessary to avoid thread safety related bugs and how does it solve it?
You can use the WeakEventManager.
public event EventHandler CanExecuteChanged
{
add
{
RelayCommandWeakEventManager.AddHandler(this, value);
}
remove
{
RelayCommandWeakEventManager.RemoveHandler(this, value);
}
}
private class RelayCommandWeakEventManager : WeakEventManager
{
private RelayCommandWeakEventManager()
{
}
public static void AddHandler(RelayCommand source, EventHandler handler)
{
if (source == null)
throw new ArgumentNullException("source");
if (handler == null)
throw new ArgumentNullException("handler");
CurrentManager.ProtectedAddHandler(source, handler);
}
public static void RemoveHandler(RelayCommand source,
EventHandler handler)
{
if (source == null)
throw new ArgumentNullException("source");
if (handler == null)
throw new ArgumentNullException("handler");
CurrentManager.ProtectedRemoveHandler(source, handler);
}
private static RelayCommandWeakEventManager CurrentManager
{
get
{
Type managerType = typeof(RelayCommandWeakEventManager);
RelayCommandWeakEventManager manager =
(RelayCommandWeakEventManager)GetCurrentManager(managerType);
// at first use, create and register a new manager
if (manager == null)
{
manager = new RelayCommandWeakEventManager();
SetCurrentManager(managerType, manager);
}
return manager;
}
}
/// <summary>
/// Return a new list to hold listeners to the event.
/// </summary>
protected override ListenerList NewListenerList()
{
return new ListenerList<EventArgs>();
}
/// <summary>
/// Listen to the given source for the event.
/// </summary>
protected override void StartListening(object source)
{
EventSource typedSource = (RelayCommand) source;
typedSource.canExecuteEventhandler += new EventHandler(OnSomeEvent);
}
/// <summary>
/// Stop listening to the given source for the event.
/// </summary>
protected override void StopListening(object source)
{
EventSource typedSource = (RelayCommand) source;
typedSource.canExecuteEventhandler -= new EventHandler(OnSomeEvent);
}
/// <summary>
/// Event handler for the SomeEvent event.
/// </summary>
void OnSomeEvent(object sender, EventArgs e)
{
DeliverEvent(sender, e);
}
}
This code was shamelessly lifted (and adapted) from https://msdn.microsoft.com/en-us/library/aa970850%28v=vs.110%29.aspx
Based on Aron's answer, I went with a solution that involves weak events, but developed differently, in order to reduce the amounts of code and make the building blocks a little more reusable.
The following implementation mixes the "classic" one, with some ideas taken from MvvmLight and I am using a WeakEvent class that is developed according to a pattern introduced in the following (excellent!!!) article by Daniel Grunwald. http://www.codeproject.com/Articles/29922/Weak-Events-in-C
The RelayCommand itself is implemented as follows:
public class RelayCommand : ICommand
{
private readonly Action _execute;
private readonly Func<bool> _canExecute;
private WeakEvent<EventHandler> _canExecuteChanged;
/// <summary>
/// Initializes a new instance of the RelayCommand class that
/// can always execute.
/// </summary>
/// <param name="execute">The execution logic.</param>
/// <exception cref="ArgumentNullException">If the execute argument is null.</exception>
public RelayCommand(Action execute)
: this(execute, null)
{
}
/// <summary>
/// Initializes a new instance of the RelayCommand class.
/// </summary>
/// <param name="execute">The execution logic.</param>
/// <param name="canExecute">The execution status logic.</param>
/// <exception cref="ArgumentNullException">If the execute argument is null.</exception>
public RelayCommand(Action execute, Func<bool> canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}
_execute = execute;
_canExecute = canExecute;
_canExecuteChanged = new WeakEvent<EventHandler>();
}
/// <summary>
/// Occurs when changes occur that affect whether the command should execute.
/// </summary>
public event EventHandler CanExecuteChanged
{
add
{
_canExecuteChanged.Add(value);
}
remove
{
_canExecuteChanged.Remove(value);
}
}
/// <summary>
/// Raises the <see cref="CanExecuteChanged" /> event.
/// </summary>
[SuppressMessage(
"Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "The this keyword is used in the Silverlight version")]
[SuppressMessage(
"Microsoft.Design",
"CA1030:UseEventsWhereAppropriate",
Justification = "This cannot be an event")]
public void RaiseCanExecuteChanged()
{
_canExecuteChanged.Raise(this, EventArgs.Empty);
}
/// <summary>
/// Defines the method that determines whether the command can execute in its current state.
/// </summary>
/// <param name="parameter">This parameter will always be ignored.</param>
/// <returns>true if this command can be executed; otherwise, false.</returns>
public bool CanExecute(object parameter)
{
return (_canExecute == null) || (_canExecute());
}
/// <summary>
/// Defines the method to be called when the command is invoked.
/// </summary>
/// <param name="parameter">This parameter will always be ignored.</param>
public virtual void Execute(object parameter)
{
if (CanExecute(parameter))
{
_execute();
}
}
}
Note that I am not holding a weak refernces to the _execute and _canExecute delegates. Using weak references to delegates causes all sorts of problems when the delegates are closures since their target object is not referenced by any object and they "die" instantly. I expect these delegates to have the owner of the RelayCommand anyway, so their lifespan is expected to be the same as the RelayCommand's.
The CanExecuteChanged event is implemented using the WeakEvent, so even if the listeners do not unregister, the relay command does not affect their lifespan.

Accessing the Command and CommandParameter properties of buttons within a user control

I have a simple user control that I'm building (something akin to the illustrations below) which is essentially a user control containing a number of buttons.
The main control itself does not have a command or command parameter property, but the four buttons inside it do and I wish to be able to access those from the view model of whatever views I happen to place this control on.
Put simply what is the best way to do this. I simply want to know which button was clicked. Each button is named (so that would I presume take care of the identification side).
Thanks for any suggestions you might have.
If I understood you correctly, you want to get a method called within your viewmodel when one of those 4 buttons is clicked.
A simplified view on the general relationship between viewmodel and view could help. From a view perspective the viewmodel is typically accessed via the datacontext property, i.e. the datacontext propery contains the viewmodel object.
Therefore, set the datacontext in xaml or code behind of your main user control to the viewmodel object that you want to use and bind from the buttons command propeties to the appropriate ICommand properties on the viewmodel that you set before.
namespace UserControlTest
{
/// <summary>
/// Interaktionslogik für MainUserControl.xaml
/// </summary>
public partial class MainUserControl : UserControl
{
public MainUserControl()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ViewModel()
{
Command = new RelayCommand((obj) => Debug.Print("done"));
}
private ICommand _command;
public ICommand Command
{
get
{
return _command;
}
set
{
_command = value;
RaisePropertyChanged("Command");
}
}
public void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class RelayCommand : ICommand
{
#region Fields
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
#endregion // Fields
#region Constructors
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 // Constructors
#region ICommand Members
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
#endregion // ICommand Members
}
}
<UserControl x:Class="UserControlTest.MainUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<StackPanel>
<Button Height="50" Command="{Binding Command}"></Button>
</StackPanel>
</Grid>
</UserControl>

Capture command Parameter value in mvvm

I have two radio button.I just want to capture the selected radio button value in viewmodel.I have defined a method GetLOB() in which I want to capture the commandParameter value.
Here is my code
<RadioButton GroupName="Os" Content="Payroll" IsChecked="{Binding ObjEntrySheetManagerViewModel.CheckedProperty}" Command="LobType" CommandParameter="Payroll" Grid.Row="4" Grid.Column="0" Margin="25,15,0,0"/>
<RadioButton GroupName="Os" Content="Sales" Grid.Row="4" Grid.Column="1" Command="LobType" CommandParameter="Payroll" Margin="5,15,0,0"/>
private RelayCommand _LobType;
public ICommand LobType
{
get
{
if (_LobType == default(RelayCommand))
{
_LobType = new RelayCommand(GetLOB);
}
return _LobType;
}
}
private void GetLOB()
{
}
Capture parameter using lambda (assuming RelayCommand used by you have overloaded constructor which will take Action<object> as argument)
public ICommand LobType
{
get
{
if (_LobType == default(RelayCommand))
{
_LobType = new RelayCommand(param => GetLOB(param));
}
return _LobType;
}
}
private void GetLOB(object parameter)
{
}
Relay command sample from MSDN (in case you need):
public class RelayCommand : ICommand
{
#region Fields
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
#endregion
#region Constructors
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
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
#endregion
}

ICommand _canExecute problem

I have the following code and it won't compile because the compiler cannot determine the return type of my CanExecute method. Can someone help me as to what is wrong?
class ViewCommand : ICommand
{
#region ICommand Members
public delegate Predicate<object> _canExecute(object param);
private ICommand _Execute;
_canExecute exe;
public bool CanExecute(object parameter)
{
return exe == null ? true : exe(parameter); // <-- Error no implicit conversion between Predicate<object> and bool
}
... // more code
}
The ICommand interface declares CanExecute as a function that takes a parameter and returns a bool.
Your _canExecute takes a parameter and returns a Predicate<object>
The way to invoke that would be to pass the parameter to the return value of exe
exe(parameter)(parameter);
I doubt that was your intention though.
I think you want to declare exe as a Predicate, and skip the delegate declaration.
private Predicate<object> exe;
This is what I think you want to look like:
class ViewCommand : ICommand
{
#region ICommand Members
private ICommand _Execute;
Predicate<object> exe;
public bool CanExecute(object parameter)
{
return exe == null ? true : exe(parameter); // <-- Error no implicit conversion between Predicate<object> and bool
}
... // more code
}

Resources