RoutedCommand 핸들러를 View-CodeBehind에서 ViewModel로 옮기는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/805838

문제

다음 RoutedCommand 예제가 작동합니다.

그러나 명령을 실행하는 버튼의 처리 보기의 코드에 있습니다. 내가 MVVM을 이해하는 방식, It ViewModel에 있어야합니다.

그러나 메소드를 ViewModel로 옮기면 (그리고 공개로 변경) 오류가 발생합니다. "ManagedCustomersview에는 OnSave의 정의가 포함되어 있지 않습니다". RoutedCommand 두 번째 매개 변수를 Typeof (ManageCustomersViewModel)로 변경하더라도 동일한 오류가 발생합니다.

명령 핸들러를 뷰 코드 베드에서 뷰 모델로 이동하려면 어떻게해야합니까?

managecustomersview.xaml :

<UserControl.CommandBindings>
   <CommandBinding Command="local:Commands.SaveCustomer" Executed="OnSave"/>
</UserControl.CommandBindings>
...
<Button Style="{StaticResource formButton}" 
   Content="Save" 
   Command="local:Commands.SaveCustomer"
   CommandParameter="{Binding Id}"/>

managecustomersview.xaml.cs :

private void OnSave(object sender
                    , System.Windows.Input.ExecutedRoutedEventArgs e)
{
    int customerId = ((int)e.Parameter);
    MessageBox.Show(String.Format
        ("You clicked the save button for customer with id {0}.", customerId));
}

commands.cs :

using System.Windows.Input;
using TestDynamicForm123.View;

namespace TestDynamicForm123
{
    public class Commands
    {
        public static RoutedCommand SaveCustomer = 
             new RoutedCommand("SaveCustomer", typeof(ManageCustomersView));
    }
}
도움이 되었습니까?

해결책

명령을 참조하는 뷰 모델에서 속성을 노출시킵니다.

class MyViewModel
{
    public RoutedCommand SaveCmd{ get{ return Commands.SaveCustomer; } }
}  

그런 다음 XAML에서

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

그러나 사용하기가 더 쉽다는 것을 알 수 있습니다 릴레이 명령 모델에서 실제 명령 로직을 정의 할 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top