Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Method of a UserControl in MVVM

Tags:

mvvm

wpf

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. SomeView.xaml's DataContext is SomeViewModel.cs

  3. I want to be able to call someControl.DoStuff() somehow, somewhere.

  4. DoStuff is not UI specific (I could have just called DoStuff from the code-behind of SomeView.Xaml.Cs if it was UI specific, but in this case, it may not be.)

Any ideas?

Thanks!

like image 798
LB. Avatar asked Sep 13 '10 23:09

LB.


2 Answers

You're probably not going to like the answer, but your ViewModel should have no knowledge of your UI. If you have a non-UI method on your UserControl, it's probably in the wrong place.

The only thing I could think of is that you may want to implement some type of messaging (like they have in MVVM Light) that could trigger the execution.

It's either that, or rethink how you've architected your code.

like image 168
Robaticus Avatar answered Sep 22 '22 12:09

Robaticus


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
    }
}
like image 22
Sai Avatar answered Sep 20 '22 12:09

Sai