Call Command from Code Behind

前端 未结 6 1149
轻奢々
轻奢々 2020-12-23 19:03

So I\'ve been searching around and cannot find out exactly how to do this. I\'m creating a user control using MVVM and would like to run a command on the \'Loaded\' event.

6条回答
  •  难免孤独
    2020-12-23 19:27

    Preface: Without knowing more about your requirements, it seems like a code smell to execute a command from code-behind upon loading. There has to be a better way, MVVM-wise.

    But, if you really need to do it in code behind, something like this would probably work (note: I cannot test this at the moment):

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

    Again - try to find a better way...

提交回复
热议问题