Sunday, July 20, 2014

Use of ICommand in Windows 8.1 app

Recently I was creating a windows 8.1 app following a MVVM pattern. I was using RelayCommand class in WPF application to create commands that XAML can bind. But unable to build the project because CommandManger class not reference to the WinRT.  The RelayCommand class used for command bind shows in below.

using System; using System.Diagnostics; using System.Windows.Input; namespace WindowsAppMvvm { public class RelayCommand : ICommand { #region Members private readonly Action execute; private readonly Func<bool> canExecute; #endregion #region Constructor public RelayCommand(Action execute) : this(execute, null) { } public RelayCommand(Action execute, Func<Boolean> canExecute) { if (execute == null) throw new ArgumentNullException("execute"); _execute = execute; _canExecute = canExecute; } #endregion #region ICommand Members public event EventHandler CanExecuteChanged { add { if (_canExecute != null) CommandManager.RequerySuggested += value; } remove { if (_canExecute != null) CommandManager.RequerySuggested -= value; } } public Boolean CanExecute(Object parameter) { return _canExecute == null ? true : _canExecute(); } public void Execute(Object parameter) { _execute(); } #endregion } }
Error shown in visual studio.


To solve this issue need to define RelayCommand class without CommandManager. Inside ICommand Members region do following changes.

 1. Remove current CanExecuteChanged event handler and replace with following line
 
public event EventHandler CanExecuteChanged;
 2. Add following method.

public void RaiseCanExecuteChanged() { if (CanExecuteChanged != null) CanExecuteChanged(this, new EventArgs()); }
 Now problem solved and project build successfully.

No comments :

Post a Comment