programing

Relay Command가 필요한 이유

mailnote 2023. 4. 11. 22:19
반응형

Relay Command가 필요한 이유

최근 WPF에서 많은 프로그래밍을 하고 있습니다만, 이 시점에서는 View와 View Model이 분리되어 있지 않습니다.뭐, 부분적으로는요.텍스트 상자의 텍스트, 레이블의 내용, 데이터그램의 목록 등과 관련된 모든 바인딩은 알림이 있는 일반 속성으로 수행됩니다.Property Changed 이벤트입니다.

버튼 클릭이나 텍스트 변경 처리를 위한 모든 이벤트는 이벤트를 링크함으로써 이루어집니다.이제 명령어를 사용하여 작업을 시작하고 싶더니 http://www.codeproject.com/Articles/126249/MVVM-Pattern-in-WPF-A-Simple-Tutorial-for-Absolute이라는 기사를 발견했습니다.MVVM의 셋업 방법에 대한 설명이 있습니다만, 이 설명과RelayCommand.

무슨 일을 하는데?내 폼의 모든 명령에 사용할 수 있습니까?(a) 특정 텍스트 상자가 입력되지 않은 경우 버튼을 비활성화하려면 어떻게 해야 합니까?


편집 1:

"내 폼의 모든 명령에 사용할 수 있습니까?"에 대한 적절한 설명은 다음과 같습니다.https://stackoverflow.com/a/22286816/3357699

다음은 제가 가지고 있는 코드입니다.https://stackoverflow.com/a/22289358/3357699

명령어는 명령어를 실행하는 로직에서 명령어를 호출하는 오브젝트와 의미론을 분리하기 위해 사용됩니다.즉, 명령어를 호출할 때 실행해야 하는 로직에서 UI 컴포넌트를 분리합니다.따라서 테스트 케이스를 사용하여 비즈니스 로직을 개별적으로 테스트할 수 있으며 UI 코드도 비즈니스 로직과 느슨하게 결합되어 있습니다.

그럼 질문을 하나씩 뽑아보도록 하겠습니다.

무슨 일을 하는데?

상기의 내용을 추가했습니다.명령어 사용이 지워지길 바랍니다.


내 폼의 모든 명령에 사용할 수 있습니까?

일부 컨트롤에서는 기본 이벤트가 등록된 버튼, MenuItem 등의 명령 종속성 속성이 노출됩니다.버튼의 경우Click이벤트입니다. 그래서, 만약 당신이ICommand버튼의 명령 DP와 함께 ViewModel에서 선언된 명령어는 버튼을 클릭할 때마다 호출됩니다.

기타 이벤트의 경우 다음을 사용하여 바인딩할 수 있습니다.Interactivity triggers에 바인드 하는 방법의 를 참조해 주세요.ICommand[ View Model ]에서 선택합니다.


(a) 특정 텍스트 상자가 입력되지 않은 경우 버튼을 비활성화하려면 어떻게 해야 합니까?

게시한 링크는 다음 링크의 완전한 구현을 제공하지 않습니다.RelayCommand을 설정하기 .CanExecute명령어가 바인드되는 UI 제어를 활성화/비활성화하는 데 중요한 역할을 하는 술어입니다.

★★★TextBox특히 어떤 성질을 가지고 있다ViewModel 및에CanExecute returns " " 。false바인딩된 속성 중 하나가 다음과 같은 경우null또는 empty 명령을 바인딩할 컨트롤을 자동으로 비활성화합니다.


「 」의 완전한 RelayCommand:

public class RelayCommand<T> : ICommand
{
    #region Fields

    readonly Action<T> _execute = null;
    readonly Predicate<T> _canExecute = null;

    #endregion

    #region Constructors

    /// <summary>
    /// Initializes a new instance of <see cref="DelegateCommand{T}"/>.
    /// </summary>
    /// <param name="execute">Delegate to execute when Execute is called on the command.  This can be null to just hook up a CanExecute delegate.</param>
    /// <remarks><seealso cref="CanExecute"/> will always return true.</remarks>
    public RelayCommand(Action<T> execute)
        : this(execute, null)
    {
    }

    /// <summary>
    /// Creates a new command.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    /// <param name="canExecute">The execution status logic.</param>
    public RelayCommand(Action<T> execute, Predicate<T> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }

    #endregion

    #region ICommand Members

    ///<summary>
    ///Defines the method that determines whether the command can execute in its current state.
    ///</summary>
    ///<param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to null.</param>
    ///<returns>
    ///true if this command can be executed; otherwise, false.
    ///</returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute == null || _canExecute((T)parameter);
    }

    ///<summary>
    ///Occurs when changes occur that affect whether or not the command should execute.
    ///</summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    ///<summary>
    ///Defines the method to be called when the command is invoked.
    ///</summary>
    ///<param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to <see langword="null" />.</param>
    public void Execute(object parameter)
    {
        _execute((T)parameter);
    }

    #endregion
}

릴레이 명령어를 사용하면 명령을 ViewModel에 직접 바인딩할 수 있다는 장점이 있습니다.이러한 방법으로 명령을 사용하면 코드 뒤에 있는 뷰에 코드가 기록되지 않습니다.

릴레이 명령을 사용할 때는 두 가지 방법을 제공해야 합니다.첫 번째 명령어는 명령어 실행 가능 여부 값(예: "CanExecuteSave")을 제공하고 다른 하나는 명령어 실행("ExecuteSave")을 담당합니다.

언급URL : https://stackoverflow.com/questions/22285866/why-relaycommand

반응형