Skip to content

Instantly share code, notes, and snippets.

@wi7a1ian
Last active August 6, 2019 08:34
Show Gist options
  • Save wi7a1ian/28c042b64cfd26e8e3bb5de64c0d50f6 to your computer and use it in GitHub Desktop.
Save wi7a1ian/28c042b64cfd26e8e3bb5de64c0d50f6 to your computer and use it in GitHub Desktop.
RelayCommand or DelegateCommand #wpf #csharp
namespace Foo
{
public class RelayCommand<T> : ICommand
{
private readonly Action<T> _execute;
private readonly Predicate<T> _canExecute;
public RelayCommand(Action<T> execute)
: this(execute, null)
{
}
public RelayCommand(Action<T> execute, Predicate<T> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute((T)parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute((T)parameter);
}
}
public class RelayCommand : RelayCommand<object>
{
public RelayCommand(Action execute) : this(execute, null) { }
public RelayCommand(Action execute, Func<bool> canExecute) : base(param => execute(), param => (canExecute != null) ? canExecute() : true) { }
}
}
private bool _isRefreshing;
private RelayCommand _refreshCommand;
public RelayCommand RefreshCommand
{
get
{
return _refreshCommand
?? (_refreshCommand = new RelayCommand( async () => {
if (_isRefreshing) {
return;
}
_isRefreshing = true;
RefreshCommand.RaiseCanExecuteChanged();
await Refresh();
_isRefreshing = false;
RefreshCommand.RaiseCanExecuteChanged();
},
() => !_isRefreshing));
}
}
<Button Command="{Binding RefreshCommand}" />
public class QuestionnaireViewModel
{
public QuestionnaireViewModel()
{
this.SubmitCommand = new RelayCommand<object>( this.OnSubmit, this.CanSubmit );
}
public ICommand SubmitCommand { get; private set; }
private void OnSubmit(object arg) {...}
private bool CanSubmit(object arg) { return true; }
}
<Button Command="{Binding SubmitCommand, Source={StaticResource MyViewModel}}" />
<Button Command="{Binding SubmitCommand}" />
<Button Command="{Binding Path=SubmitCommand}" CommandParameter="SubmitOrder"/>
<Button Command="{Binding SubmitCommand}" CommandParameter="{Binding SelectedSubmitOrder}" />
public class MyViewModel
{
private ICommand _doSomething;
public ICommand DoSomethingCommand
{
get
{
if (_doSomething == null)
{
_doSomething = new RelayCommand(
p => this.DoSomeImportantMethod(),
p => this.CanDoSomething);
}
return _doSomething;
}
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment