logo MSJO.kr

ICommand, RelayCommand in WPF

2019-09-23
MsJ
   

WPF-MVVM 방식에 있어서 ICommand는 필수요소인 데 일반적으로 xaml의 Element(Button, TextBox 등)와 연결된 명령 동작의 이벤트를 처리한다. 우선 ICommand를 상속받은 RelayCommand 클래스를 만들고 ViewModel에서 이를 활용한다. 아래의 소스는 RelayCommand 클래스와 이를 활용한 이벤트 처리 예제이다.

<!-- <Fluent:Button Header="프로그램 종료" Command="{Binding TestCommand}"  CommandParameter="{Binding ElementName=TestButton, Path=Header}" x:Name="TestButton"/> -->
<Fluent:Button Header="프로그램 종료" Command="{Binding TestCommand}"  CommandParameter="{Binding RelativeSource={RelativeSource Self}}" x:Name="TestButton"/>
// ViewModel: Binding Path에 따라 object -> string
public ICommand TestCommand => new RelayCommand<object>(TestRun, TestCheck);

private void TestRun(object x)
{
    MessageBox.Show((x as Button).Name);
}

private bool TestCheck(object x)
{
    return x is Button;
}
RelayCommand Class
// RelayCommand.cs
using System;
using System.Windows.Input;

namespace MSJoTemplateWPF472.ViewModels
{
    public class RelayCommand<T> : ICommand
    {
        readonly Action<T> _execute = null;
        readonly Predicate<T> _canExecute = null;

        public RelayCommand(Action<T> execute, Predicate<T> canExecute = null)
        {
            _execute = execute ?? throw new ArgumentNullException(nameof(execute));
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute?.Invoke((T) parameter) ?? true;
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {
            _execute((T) parameter);
        }
    }
}

Prεv(Θld)   Nεxt(Nεw)
Content
Search     RSS Feed     BY-NC-ND