mardi 29 octobre 2019

How to keep data source separate from reusable UserControl in WPF?

I've created a Calendar UserControl by myself. It consists of several sub UserControls. The whole thing is designed to be reusable in other projects. The all containing control that is used and visible from outside (by the user) now has a ViewModel that controls all logic for the Calendar. I think this time I really managed to create a clean, loosely installable control. The only thing I wonder is how to put the required data into the (ViewModel of) the control in a way that is abstract and 'custom implementable'.

I can think of the followong solutions:

  1. Create an interface like ICalendarDataProvider. Then a dependency property on the Calendar control accepts any instance that implements this interface. But a dependency property would be on the codebehind level of the Calendar control, and can only access the DataContext (the ViewModel) of the Calendar by using a dependency property changed callback. This seems ugly, because in that callback I have to cast the dependency object to my Calendar control, get its DataContext property and cast this to the ViewModel type that is the Calendar DataContext. The ViewModel type can not change then, because then the casting in the callback would have to change too. This is actually tight coupling.

  2. Just setting the ViewModel of the Calendar control explicitly from outside by setting the DataContext property. This way the ViewModel can be extended by a data providing class and then set as DataContext of the Calendar. In this class hierarchy the parent class is still a basic class that contains all required logic, and is extended by a class that takes care of the data.

I would like to know how this is done in well MVVM designed projects. Or what's the best practise.

Aucun commentaire:

Enregistrer un commentaire