Calling a Method of a UserControl in MVVM

前端 未结 7 449
温柔的废话
温柔的废话 2021-01-17 14:26

I\'m having an issue with calling a method on a UserControl. Hear me out:

  1. I have a UserControl someControl in SomeView.xaml

  2. Som

7条回答
  •  悲&欢浪女
    2021-01-17 15:20

    One the SO answer to Achive this by decouples the ViewModel's knowledge about View is by using the Action delegates answered by Mert here

    Pasted his code here, if the link breaks by any chance.

    class MyCodeBehind
    {
       public MyCodeBehind()
       {
          Action action = new Action(()=> this.SomeMethodIWantToCall());
          var myVM = new MyVM(action); // This is your ViewModel
          this.DataContext = myVM;
       }
    
       private void SomeMethodIWantToCall(){...}
    }
    
    class MyVM
    {
        private Action action;
    
        public MyVM(Action someAction)
        {
           this.action = someAction;
        }
    
        private void SomeMethodInVM()
        {
            this.action(); // Calls the method SomeMethodIWantToCall() in your code behind
        }
    }
    

提交回复
热议问题