ProgramingTip

코드 숨김에서 명령 호출

bestdevel 2020. 11. 30. 19:24
반응형

코드 숨김에서 명령 호출


그래서 나는 주위를 보증하고 수행하는 방법을 알 수 없습니다. MVVM을 사용하여 사용자 정의 컨트롤을 만들고 'Loaded'이벤트에서 명령을 실행하고 싶습니다. 나는 약간의 코드가 필요하다는 것을 알 수 없습니다. 이 명령은 뷰의 데이터로 집합 ViewModel에 있습니다.하지만로드 된 이벤트가있는 코드에서 호출 할 수있는 라우팅하는 방법을 정확히 모르겠습니다. 기본적으로 내가 원하는 것은 이런 것입니다 ...

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    //Call command from viewmodel
}

주위를 둘러 보면 어디서나 이것에 대한 구문을 사용할 수없는 것입니다. 먼저 xaml의 명령을 바인딩해야해야합니까? 사용자 컨트롤의 명령 바인딩 옵션은 버튼과 같은 것에서 명령을 바인딩 할 수 없습니다.

<UserControl.CommandBindings>
    <CommandBinding Command="{Binding MyCommand}" /> <!-- Throws compile error -->
</UserControl.CommandBindings>

이 작업을 수행하는 간단한 방법이 확신하지만, 내 인생에서 확신 할 수 없습니다.


글쎄, DataContext가 이미 설정되어 있기 때문에 다음 명령을 호출 할 수 있습니다.

var viewModel = (MyViewModel)DataContext;
if (viewModel.MyCommand.CanExecute(null))
    viewModel.MyCommand.Execute(null);

(필요에 따라 매개 변수 변경)


서문 : 요구 사항에 대해 더 많이 알지 못하는 경우로드시 코드 숨김에서 명령을 실행하는 코드 냄새처럼. MVVM과 같은 더 나은 방법이 필요합니다.

그러나 다음과 같이 작동 할 수 없습니다 (참고 : 지금은 테스트 할 수 없습니다).

private void UserControl_Loaded(object sender, RoutedEventArgs e)     
{
    // Get the viewmodel from the DataContext
    MyViewModel vm = this.DataContext as MyViewModel;

    //Call command from viewmodel     
    if ((vm != null) && (vm.MyCommand.CanExecute(null)))
        vm.MyCommand.Execute(null);
} 

다시-더 나은 방법을 찾으십시오 ...


이 시도 :

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    //Optional - first test if the DataContext is not a MyViewModel
    if( !this.DataContext is MyViewModel) return;
    //Optional - check the CanExecute
    if( !((MyViewModel) this.DataContext).MyCommand.CanExecute(null) ) return;
    //Execute the command
    ((MyViewModel) this.DataContext).MyCommand.Execute(null)
}

공유하고 싶은 더 한 솔루션이 있습니다. ViewModels에서 종종 명령을 실행하기 때문에 문을 작성하는 데 지쳤습니다. 그래서 ICommand 인터페이스에 대한 확장을 작성했습니다.

using System.Windows.Input;

namespace SharedViewModels.Helpers
{
    public static class ICommandHelper
    {
        public static bool CheckBeginExecute(this ICommand command)
        {
            return CheckBeginExecuteCommand(command);
        }

        public static bool CheckBeginExecuteCommand(ICommand command)
        {
            var canExecute = false;
            lock (command)
            {
                canExecute = command.CanExecute(null);
                if (canExecute)
                {
                    command.Execute(null);
                }
            }

            return canExecute;
        }
    }
}

그리고이 코드에서 명령을 실행하는 방법입니다.

((MyViewModel)DataContext).MyCommand.CheckBeginExecute();

나는 이것이 당신의 개발 속도를 조금 더 가속화하기를 바랍니다. :)

추신 : ICommandHelper의 네임 스페이스도 포함하는 것을 잊지 마십시오. (제 경우에는 SharedViewModels.Helpers입니다)


MessaginCenter에 코드를 내장했을 수도 있습니다. MessagingCenter 모델을 구독하고 작업 할 수 있습니다. Command 속성이있는보기 버튼을 클릭하는 대신 코드 뒤에서 무언가를 실행하려는 경우 완벽하게 작동했습니다.

누군가에게 도움이되기를 바랍니다.

참고 URL : https://stackoverflow.com/questions/10126968/call-command-from-code-behind

반응형