WPFCommand는 C# 호스트 컴퓨터를 자세히 설명합니다.

소개

WPF(Windows Presentation Foundation)는 Windows 응용 프로그램을 빌드하기 위한 Microsoft UI 프레임워크입니다. WPF에서는 Command를 사용하여 작업 바인딩을 실현할 수 있으며 Command를 사용하여 UI 인터페이스에서 작업을 분리하여 코드를 더 명확하고 이해하기 쉽게 만들 수 있습니다. 이 문서에서는 각 Command 명령의 구현을 포함하여 WPF의 Command를 자세히 소개하고 구체적인 예를 제공합니다.

RoutedCommand

RoutedCommand는 UI 인터페이스에서 명령을 분리할 수 있고 다른 UI 요소 간에 공유할 수 있는 WPF의 명령입니다. RoutedCommand는 CommandBinding을 통해 UI 요소에 바인딩되어야 합니다. 다음 코드를 사용하여 RoutedCommand를 만들 수 있습니다.

public static readonly RoutedCommand MyCommand = new RoutedCommand();

그런 다음 다음 코드를 사용하여 RoutedCommand를 UI 요소에 바인딩할 수 있습니다.

<MenuItem Command="{x:Static local:MainWindow.MyCommand}" />

또한 다음과 같이 명령을 처리하기 위해 코드에서 CommandBinding을 구현해야 합니다.

CommandBinding binding = new CommandBinding(MyCommand, MyCommand_Executed, MyCommand_CanExecute);
this.CommandBindings.Add(binding);

그 중 MyCommand_Executed와 MyCommand_CanExecute는 명령을 처리하는 메서드로, 이 두 메서드에서 특정 명령 로직을 구현해야 합니다.

RelayCommand

RelayCommand는 UI 인터페이스에서 명령을 분리하고 ViewModel의 메서드에 바인딩하는 경량 명령 구현입니다. 다음 코드를 사용하여 RelayCommand를 만들 수 있습니다.

public class RelayCommand : ICommand
{
    private Action<object> _execute;
    private Func<object, bool> _canExecute;

    public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
    {
        _execute = execute ?? throw new ArgumentNullException("execute");
        _canExecute = canExecute;
    }

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

    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

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

그런 다음 다음과 같이 ViewModel에서 RelayCommand의 인스턴스를 만들 수 있습니다.

public class ViewModel
{
    public ICommand MyCommand { get; private set; }

    public ViewModel()
    {
        MyCommand = new RelayCommand(ExecuteMyCommand, CanExecuteMyCommand);
    }

    private bool CanExecuteMyCommand(object parameter)
    {
        // Add logic to determine if command can execute
        return true;
    }

    private void ExecuteMyCommand(object parameter)
    {
        // Add logic to execute command
    }
}

마지막으로 다음과 같이 XAML에서 RelayCommand를 바인딩할 수 있습니다.

<Button Command="{Binding MyCommand}" />

위임 명령

DelegateCommand는 UI 인터페이스에서 명령을 분리하고 ViewModel의 메서드에 바인딩할 수 있는 명령을 구현하는 또 다른 방법입니다. DelegateCommand 및 RelayCommand의 구현은 유사하며 다음 코드를 사용하여 DelegateCommand를 생성할 수 있습니다.

public class DelegateCommand : ICommand
{
    private Action<object> _execute;
    private Func<object, bool> _canExecute;

    public DelegateCommand(Action<object> execute, Func<object, bool> canExecute = null)
    {
        _execute = execute ?? throw new ArgumentNullException("execute");
        _canExecute = canExecute;
    }

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

    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

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

그런 다음 ViewModel에서 다음과 같이 DelegateCommand의 인스턴스를 만들 수 있습니다.

public class ViewModel
{
    public ICommand MyCommand { get; private set; }

    public ViewModel()
    {
        MyCommand = new DelegateCommand(ExecuteMyCommand, CanExecuteMyCommand);
    }

    private bool CanExecuteMyCommand(object parameter)
    {
        // Add logic to determine if command can execute
        return true;
    }

    private void ExecuteMyCommand(object parameter)
    {
        // Add logic to execute command
    }
}

마지막으로 다음과 같이 XAML에서 DelegateCommand를 바인딩할 수 있습니다.

<Button Command="{Binding MyCommand}" />

위에서 설명한 세 가지 명령 구현 방법 외에도 ICommand 인터페이스의 사용자 지정 구현, EventToCommand, InvokeCommandAction 등과 같이 일반적으로 사용되는 다른 명령 구현 방법이 있습니다. 이러한 명령 구현 방법에는 고유한 장점과 단점이 있으며 실제 필요에 따라 적절한 방법을 선택해야 합니다. Command를 사용할 때 과도한 사용을 피하고 코드의 가독성과 유지 관리에 영향을 미치는 지나치게 복잡한 명령 체인을 피하도록 주의를 기울여야 합니다. 이 기사를 통해 WPF의 명령에 대해 더 깊이 이해할 수 있기를 바랍니다.

위의 소개를 통해 WPF에서 Command의 사용이 매우 유연하고 실제 필요에 따라 다른 명령 구현 방법을 선택할 수 있음을 알 수 있습니다. 명령을 사용하면 UI 인터페이스에서 작업을 분리하여 코드를 더 명확하고 이해하기 쉽게 만들 수 있습니다. Command를 사용할 때 과도한 사용을 피하고 코드의 가독성과 유지 관리에 영향을 미치는 지나치게 복잡한 명령 체인을 피하도록 주의를 기울여야 합니다. 이 글이 모두에게 도움이 되었으면 합니다.

Supongo que te gusta

Origin blog.csdn.net/Documentlv/article/details/130752207
Recomendado
Clasificación