RelayCommand 및 RelayCommand<T>

RelayCommandRelayCommand<T>은(는) 뷰에 메서드 또는 대리자를 노출할 수 있는 ICommand 구현입니다. 이러한 형식은 viewmodel과 UI 요소 간에 명령을 바인딩하는 방법으로 작동합니다.

플랫폼 API:RelayCommand, RelayCommand<T>, IRelayCommandIRelayCommand<T>

작동 방식

RelayCommand 다음과 RelayCommand<T> 같은 주요 기능이 있습니다.

  • 그것들은 ICommand 인터페이스의 기본 구현을 제공합니다.
  • 또한 IRelayCommand(IRelayCommand<T>도 포함) 인터페이스를 구현하며, 이 인터페이스는 CanExecuteChanged 이벤트를 발생시키는 NotifyCanExecuteChanged 메서드를 노출합니다.
  • 표준 메서드와 람다 식을 래핑할 수 있도록 하는 ActionFunc<T> 같은 대리자를 받는 생성자를 제공합니다.

ICommand 사용하기

다음은 간단한 명령을 설정하는 방법을 보여줍니다.

public class MyViewModel : ObservableObject
{
    public MyViewModel()
    {
        IncrementCounterCommand = new RelayCommand(IncrementCounter);
    }

    private int counter;

    public int Counter
    {
        get => counter;
        private set => SetProperty(ref counter, value);
    }

    public ICommand IncrementCounterCommand { get; }

    private void IncrementCounter() => Counter++;
}

그리고 해당 UI는 WinUI XAML을 사용하면 다음과 같을 수 있습니다:

<Page
    x:Class="MyApp.Views.MyPage"
    xmlns:viewModels="using:MyApp.ViewModels">
    <Page.DataContext>
        <viewModels:MyViewModel x:Name="ViewModel"/>
    </Page.DataContext>

    <StackPanel Spacing="8">
        <TextBlock Text="{x:Bind ViewModel.Counter, Mode=OneWay}"/>
        <Button
            Content="Click me!"
            Command="{x:Bind ViewModel.IncrementCounterCommand}"/>
    </StackPanel>
</Page>

Button은(는) private IncrementCounter 메서드를 래핑하는 viewmodel의 ICommand에 바인딩됩니다. 속성 TextBlock 값이 표시되고 속성 값 Counter 이 변경 될 때마다 업데이트됩니다.

예제

  • 샘플 앱(여러 UI 프레임워크의 경우)을 확인하여 작동 중인 MVVM 도구 키트를 확인합니다.
  • 단위 테스트에서 더 많은 예제를 찾을 수도 있습니다.