MVVM Madness: Commands

后端 未结 7 1091
星月不相逢
星月不相逢 2021-01-30 01:38

I like MVVM. I don\'t love it, but like it. Most of it makes sense. But, I keep reading articles that encourage you to write a lot of code so that you can write XAML and don\'t

7条回答
  •  迷失自我
    2021-01-30 02:07

    I agree with you that many MVVM-Command solutions are too complicated. Personally, I use a mixed approach and define my Commands in the View rather than in the ViewModel, using methods and properties from the ViewModel.

    XAML:

    
        
    
    
        
    
    

    Code (View):

    Private Sub cmdLookupAddress_CanExecute(ByVal sender As System.Object, ByVal e As System.Windows.Input.CanExecuteRoutedEventArgs) Handles cmdLookupAddress.CanExecute
        e.CanExecute = myViewModel.SomeProperty OrElse (myViewModel.SomeOtherProperty = 2)
    End Sub
    
    Private Sub cmdLookupAddress_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs) Handles cmdLookupAddress.Executed
        myViewModel.LookupAddress()
    End Sub
    

    It's not pure MVVM, but it simple, it works, it does not need special MVVM-command-classes and it makes your code much easier to read for non-MVVM-experts (= my co-workers).

提交回复
热议问题