-
-
Save Ovis/1525702ad32555e3b906cb01c43b528c to your computer and use it in GitHub Desktop.
DelegateCommand on WPF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Window x:Class="WpfApp1.MainWindow" | |
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" | |
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" | |
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" | |
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" | |
xmlns:local="clr-namespace:WpfApp1" | |
mc:Ignorable="d" | |
Title="MainWindow" Height="450" Width="800"> | |
<Button x:Name="button"> | |
TEST | |
</Button> | |
</Window> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Windows; | |
using System.Windows.Input; | |
namespace WpfApp1 | |
{ | |
public sealed class DelegateCommand : ICommand | |
{ | |
private readonly Func<bool> canExecute; | |
private readonly Action execute; | |
public DelegateCommand(Func<bool> canExecute, Action execute) | |
{ | |
this.canExecute = canExecute; | |
this.execute = execute; | |
} | |
public event EventHandler CanExecuteChanged; | |
public bool CanExecute(object parameter) => | |
canExecute(); | |
public void Execute(object parameter) => | |
execute(); | |
} | |
public sealed class DelegateCommand<T> : ICommand | |
{ | |
private readonly Func<T, bool> canExecute; | |
private readonly Action<T> execute; | |
public DelegateCommand(Func<T, bool> canExecute, Action<T> execute) | |
{ | |
this.canExecute = canExecute; | |
this.execute = execute; | |
} | |
public event EventHandler CanExecuteChanged; | |
public bool CanExecute(object parameter) => | |
parameter is T value ? canExecute(value) : false; | |
public void Execute(object parameter) => | |
execute((T)parameter); | |
} | |
/// <summary> | |
/// Interaction logic for MainWindow.xaml | |
/// </summary> | |
public partial class MainWindow : Window | |
{ | |
public MainWindow() | |
{ | |
InitializeComponent(); | |
button.Command = new DelegateCommand( | |
() => true, | |
() => button.Content = "Clicked!"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment