programing

코드 배후에 있는 콜명령어

lastcode 2023. 4. 17. 21:54
반응형

코드 배후에 있는 콜명령어

그래서 계속 찾아봤지만 어떻게 해야 하는지 정확히 알 수가 없어요.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);
} 

다시 - 더 나은 방법을 찾아보세요...

저는 좀 더 콤팩트한 솔루션을 공유하고 싶습니다.View Models에서 명령을 실행하는 경우가 많기 때문에 동일한 if 문을 쓰는 데 지쳤습니다.그래서 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();

이것이 당신의 발전을 조금이라도 앞당기길 바랍니다.:)

추신. 아이컴맨드를 잊지 말고도우미의 네임스페이스도 있습니다.(이 경우는 Shared View Models 입니다.도우미)

이것을 시험해 보세요.

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)
}

코드 뒤에 있는 명령어를 호출하려면 이 코드 라인을 사용합니다.

예: Call a Button 명령어

Button.Command?.Execute(Button.CommandParameter);

또한 Messagin Center에 코드를 삽입했을 수도 있습니다.Messaging Center 모델을 구독하고 작업할 수 있습니다.Command 속성으로 뷰 버튼을 클릭하지 않고 코드 뒤에서만 실행할 생각이라면 완벽하게 작동했습니다.

도움이 됐으면 좋겠어요.

언급URL : https://stackoverflow.com/questions/10126968/call-command-from-code-behind

반응형