ViewModel and View Binding Question

Topics: Prism v4 - WPF 4
Feb 11, 2012 at 7:52 PM

I am building a Prism application that has a MainRegion, MenuRegion, and ToolBarRegion.  Each view that is inserted into the MainRegion has it's own menu and toolbar that get inserted into it's corresponding region.  I wired this by using a single instance of a ViewModel that is registered with the unity container as follows container.RegisterInstance<MyViewModel>(myViewModel).  The mainView, menuView, and toolbarView each get the same viewModel instance injected into it when it is created.  Each view is similar to the following:

public partial class View1ToolBar : UserControl

    public View1ToolBar()

    public MyViewModel ViewModel
        set { this.DataContext = value; }


Therefore, all commands get bound to the myViewModel using DelegateCommand's.  Is this a good practice?


Feb 11, 2012 at 11:26 PM
Edited Feb 11, 2012 at 11:45 PM

I personally like the composite form with the use of Dependency Injection defined within the constructor of the View, typically via an IViewModel interface (per Prism4 documentation). This holds true for any View/ViewModel that you may use as follows:


interface IYourViewModel {

 ICommand cmdSubmitAction {get; private set;}  // This is one command that your ViewModel must implement



public class YourViewModel : IYourViewModel{

 public ICommand cmdSubmitAction {get; private set;} 

  public YourViewModel(){

cmdSubmitAction = new DelegateCommand(()=>{

//Define your code to handle this Command 





public class YourVIew{

public YourView(IYourViewModel VM){

//  Use Dependency Injection within the Constructor to define its DataContext from the Interface resolved by Unity

this.DataContext = VM;



Unity Registration (Assume UC = IUnityContainer)

UC.RegisterType<IYourViewModel, YouViewModel>();

// This tells Unity that you want the concrete implementation YouViewModel when you ask for IYouViewModel

Add Your View To A Region

 //This is one way, but you get the idea... As your code will ask Unity for your View, the View's constructor does the rest.  


** The above was free formed typed, I am assuming you can infer the concept and not get hung up on any small syntax issue


The idea here is that you can now create more than one ViewModel that implement IYourViewModel and reuse your xaml View file with any number of ViewModels as makes sense to promote reusability. This is a good practice for abstraction and clean separation. So if you create a xaml file and Interface that any ViewModel must implement, then another developer on your team could then create the concrete ViewModel Implementing your defined Interface without having to be involved with the xaml portion. Now, I concede that you are probably doing everything yourself, maybe not... But in a team and especially when working between disconnected groups this clear/clean separation helps keep things organized.

Feb 13, 2012 at 2:43 PM

Thanks for the advice