I wanna implement an interface(Add behavior) for set of WPF usercontrols.
I’m using MVVM design pattern.
Where I should implement the interface? in usercontrol code behind or in View model class?
Ex:
My Interface is
interface IWizard
{
event RoutedEventHandler MoveNext;
event RoutedEventHandler MoveBack;
event RoutedEventHandler Cancelled;
bool IsLast;
bool IsFirst;
}
Now in other place I wanna access user controls which are implemented this interface as this.
((IWizard)userControl).MoveNext += ...
((IWizard)userControl).MoveBack += ...
((IWizard)userControl).IsLast = true;
etc..
Implement in UserControl Code behind
I can’t acess the interface’s properties/methods directly in view model. I have to link them manually. right ?
PS: In this example I wanna Bind(TwoWay Bind) IsLast Property with a visibility of a button.
Implement in View model class
I can’t access the usercontrol as a Interface object.
ex: ((IWizard)userControl).MoveNext += ...
What is the best practice on Implementing an Interface on Usercontrol with MVVM design Pattern?
In perfect-world MVVM, ViewModel has no knowledge whatsoever about View. Whether View implements any interface at all is irrelevant from ViewModel’s point of view.
In your scenario, what I think is more important is who will respond to
MoveNext,MoveBackandCanceledevents. Most likely, that would be ViewModel. What that means you probably could use methods such asWizardMoved(object sender, EventArgs e)in those ViewModels. Look what we’ve done here – ViewModel needs to have kind of indirect knowledge about View. That is not a good sign.Perhaps instead, you could approach problem differently. Maybe what you need is
IWizardMovementinterface that will define methods to handle wizard moving events – and this interface will be implemented by ViewModels. So that when you pass ViewModel to View, it can easily subscribe ViewModel’s handlers to its own events (note that not it doesn’t really matter what interface View implements).Now, since in MVVM View knows about ViewModel (and never the other way around), you can easily utilize this knowledge:
ViewModel is separated from View for good now, and how your View looks like is not important anymore (as it should never been in first place).