I'm having an issue with calling a method on a UserControl. Hear me out:
I have a UserControl someControl
in SomeView.xaml
SomeView.xaml's DataContext is SomeViewModel.cs
I want to be able to call someControl.DoStuff()
somehow, somewhere.
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!
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With