I am thinking about writing a WPF User Control for my application. I am using MVVM in my application.
User control's may require Dependency Properties that can be set my Parent View. when using MVVM, the idea is that the Parent View will eventually create a binding between the UserControls
DP with Parent View's VM)
Dependency Properties
need to be created in the View class as VM do not inherit from DependencyObject
. This means adding code within the XAML code behind.
I was wondering if you can give advice as to how I should design a user control when developing WPF application using MVVM...
Case 1: If you are creating this control just to be consumed in your application then you can go ahead and create a ViewModel
for it, but then you don't need to create DP's, your ViewModel
can just implement INotifyPropertyChanged
and your parent Vm can still bind to them.
In our case, for user controls we have created separate VM's and an instance of it was present in ParentVM
. So parent view will have this control in it and will bind the UserControlVM
to this control(ParentVM.UserControlVM
) and usercontrol will take care of other bindings.
Case 2: If your control will be used by other applications/developers and you don't want to keep it simple then go ahead with creating custom controls following control template implementation. This way you can create look-less controls and use dependency properties
too. Moreover whoever uses that control doesn't need to know about the related view model and use it.
Some of the similar questions/posts:
WPF design question (custom control or mvvm): WPF design question (custom control or mvvm)
Custom control in WPF using MVVM concept: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/6293b176-e1e9-4610-af49-d53e6d294969/
WPF User Control hell with MVVM and Dependency Properties: WPF User Control hell with MVVM and Dependency Properties