John Sourcer
John Sourcer

Reputation: 451

ViewModel used by multiple views

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

Answers (4)

mcalex
mcalex

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

Davio
Davio

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

Florian Gl
Florian Gl

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

AD.Net
AD.Net

Reputation: 13399

You can have a base view that'll initialize the viewmodel

Upvotes: 0

Related Questions