-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
RelayCommand.cs
55 lines (47 loc) · 1.73 KB
/
RelayCommand.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Copyright © 2017 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Windows.Input;
namespace CefSharp.Wpf.Example
{
public class RelayCommand : ICommand
{
private readonly Action<object> commandHandler;
private readonly Func<object, bool> canExecuteHandler;
public event EventHandler CanExecuteChanged;
public RelayCommand(Action<object> commandHandler, Func<object, bool> canExecuteHandler = null)
{
this.commandHandler = commandHandler;
this.canExecuteHandler = canExecuteHandler;
}
public RelayCommand(Action commandHandler, Func<bool> canExecuteHandler = null)
: this(_ => commandHandler(), canExecuteHandler == null ? null : new Func<object, bool>(_ => canExecuteHandler()))
{
}
public void Execute(object parameter)
{
commandHandler(parameter);
}
public bool CanExecute(object parameter)
{
return
canExecuteHandler == null ||
canExecuteHandler(parameter);
}
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
public class RelayCommand<T> : RelayCommand
{
public RelayCommand(Action<T> commandHandler, Func<T, bool> canExecuteHandler = null)
: base(o => commandHandler(o is T t ? t : default(T)), canExecuteHandler == null ? null : new Func<object, bool>(o => canExecuteHandler(o is T t ? t : default(T))))
{
}
}
}