Reputation: 451
In an MVVM pattern, I have a single common ViewModel used by 3 usercontrols. I was instantiating the ViewModel and passing it as a parameter to the constructors of the user controls but this breaks XAML which requires that objects are constructed with parameterless constuctors.
What is the accepted best practise for creating a shared ViewModel?
Upvotes: 0
Views: 106
Reputation: 6778
Dependency Injection with Unity ( http://msdn.microsoft.com/en-us/library/ff660899(v=pandp.20).aspx ) or MEF are the standard MVVM ways of coupling views to viewmodels
But don't forget that MVVM is a pattern, not a rigid framework. You can have a one-line hookup in the view's code behind:
InitializeComponent();
this.DataContext = new ViewModel(whatever);
without the sky falling.
Upvotes: 1
Reputation: 4737
You can just add parameterless constructors for your UserControls
public MyUserControl() : base(new MyViewModel())
{}
public MyUserControl(MyViewModel viewModel)
{}
Note: This may break several design paradigms. :)
Upvotes: 1
Reputation: 6014
You could create a ViewModel for your MainWindow which contains a property of Type SharedViewModel
: public SharedViewModel SharedViewModel {get;set;}
. You set the DataContext of your Window to your MainViewModel and bind to the shared ViewModel like:
<Window>
<Grid>
<UserControl1 DataContext="{Binding Path=SharedViewModel}"/>
<UserControl2 DataContext="{Binding Path=SharedViewModel}"/>
<UserControl3 DataContext="{Binding Path=SharedViewModel}"/>
</Grid>
</Window>
Upvotes: 2