Skip to content

Instantly share code, notes, and snippets.

@Ovis
Forked from kekyo/MainWindow.xaml
Created November 24, 2019 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ovis/1525702ad32555e3b906cb01c43b528c to your computer and use it in GitHub Desktop.
Save Ovis/1525702ad32555e3b906cb01c43b528c to your computer and use it in GitHub Desktop.
DelegateCommand on WPF
<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>
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