.NET MAUI - MVVM Command

2022. 8. 15. 00:00MAUI

반응형

RelayCommand 및 RelayCommand<T>

RelayCommand 및 RelayCommand<T>는 메서드를 노출하거나 뷰에 위임할 수 있는 ICommand 구현이다. 

이러한 유형은 viewmodel과 UI 요소 간에 명령을 바인딩한다.

 

  • ICommand 인터페이스의 기본 구현을 제공한다.
  • CanExecuteChanged 이벤트를 발생시키는 인터페이스를 구현한다.
  • Action 및 Func<T>와 같은 대리자를 사용하는 생성자를 노출한다.
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Windows.Input;

namespace MauiApp1.MVVM.Commanding;
public class IncrementCounterViewModel : ObservableObject
{
    public IncrementCounterViewModel()
    {
        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++;
}
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiApp1.MVVM.Commanding.IncrementCounterPage"
             xmlns:local="clr-namespace:MauiApp1.MVVM.Commanding"
             Title="IncrementCounterPage">
    <ContentPage.BindingContext>
        <local:IncrementCounterViewModel />
    </ContentPage.BindingContext>
    <VerticalStackLayout>
        <Label Text="{Binding Counter, Mode=OneWay}"/>
        <Button
            Text="Click me!"
            Command="{Binding IncrementCounterCommand}"/>
    </VerticalStackLayout>
</ContentPage>

Button 을 클릭 하면 IncreamentCounterCommand 가 실행된다.

그러면 RelayCommand 에 연결된 IncrementCounter() 가 실행되어 Counter 가 증가하게 된다. 

AsyncRelayCommand 및 AsyncRelayCommand<T>

AsyncRelayCommand 및 AsyncRelayCommand<T>는 비동기 작업을 지원하는 RelayCommand 의 확장이다.

 

  • Task-returning delegates 를 지원하여 라이브러리에 포함된 동기 명령의 기능을 확장한다.
  • 취소를 지원하기 위해 추가 CancellationToken 매개 변수로 비동기 함수를 래핑할 수 있며 CanBeCanceled 및 IsCancellationRequested 속성과 Cancel 메서드를 노출한다.
  • 보류 중인 작업의 진행률을 모니터링하는 데 사용할 수 있는 ExecutionTask 속성과 작업이 완료될 때 확인하는 데 사용할 수 있는 IsRunning을 노출한다. 이는 로드 표시기와 같은 UI 요소에 명령을 바인딩하는 데 특히 유용하다.
  • 이들은 IAsyncRelayCommand 및 IAsyncRelayCommand<T> 인터페이스를 구현한다. 즉, viewmodel은 유형 간의 긴밀한 결합을 줄이기 위해 이를 사용하여 명령을 쉽게 노출할 수 있다. 예를 들어, 필요한 경우 동일한 공개 API 를 노출하는 사용자 정의 구현으로 명령을 쉽게 대체할 수 있다.
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Windows.Input;

namespace MauiApp1.MVVM.Commanding;
public class IncrementCounterViewModel : ObservableObject
{
    public IncrementCounterViewModel()
    {
        IncrementCounterCommandAsync = new AsyncRelayCommand(IncrementCounterAsync);
    }

    private int counter;

    public int Counter
    {
        get => counter;
        private set => SetProperty(ref counter, value);
    }
    public IAsyncRelayCommand IncrementCounterCommandAsync { get; }
    private async Task IncrementCounterAsync()
    {
        await Task.Delay(3000);
        Counter++;
    }
}
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiApp1.MVVM.Commanding.AsyncIncrementCounterPage"
             xmlns:local="clr-namespace:MauiApp1.MVVM.Commanding"
             Title="AsyncIncrementCounterPage">
    <ContentPage.BindingContext>
        <local:IncrementCounterViewModel />
    </ContentPage.BindingContext>
    <VerticalStackLayout>
        <Label Text="{Binding Counter}"/>
        <Label Text="{Binding IncrementCounterCommandAsync.ExecutionTask.Status}"/>
        <Button
            Text="Click me!"
            Command="{Binding IncrementCounterCommandAsync}"/>

        <ActivityIndicator IsRunning="{Binding IncrementCounterCommandAsync.IsRunning}" />
    </VerticalStackLayout>
</ContentPage>

 

Button 을 클릭하면 3초간 아래쪽 label 에  WaitingForActivation 을 표시하고 그동안  ActivityIndicator 가 돌아간다.

이후 RanToCompletion 이 표시되고 Counter 가 증가 된다.

 

ExecutionTask.Status 가 Label 표시되는 WaitingForActivationRanToCompletion  이다. 

IsRunning 이 ActivityIndicator 에게 실행중을 알리도록 binding 되어 있고

실행이 완료되면 Counter 가 증가되도록 되어 있다. 

 

실행 중
실행 완료

 

 

관련영상

https://youtu.be/1G7esB_rMvg

 

 

 

반응형

'MAUI' 카테고리의 다른 글

.NET MAUI - MVVM SourceGenerator  (0) 2022.08.17
.NET MAUI - MVVM Messenger  (0) 2022.08.16
.NET MAUI - MVVM ObservableValidator  (0) 2022.08.12
.NET MAUI - MVVM ObservableRecipient  (0) 2022.08.11
.NET MAUI - MVVM ObservableObject  (0) 2022.08.10