tags:

views:

193

answers:

3

Hi,

When writing a MVVM WPF app, there's always a point where the view model has to be set to as the data context of the view. For me, usually that's in code. But I realized that if I declare the view model as a static resource inside the xaml and set the binding there, I don't need to do it in code anymore. This means I don't have to coordinate the view and the viewmodel in a third class somewhere, like in the App.

Is it acceptable to do this?

Thanks!

A: 

I'd say so. It sort of implies specific knowledge of the ViewModel from the View, but you have to set it somehow and I like the codebehindless approach here.

If you are using dependency injection this would not be appropriate, but if you aren't I'd stick with this approach.

Anderson Imes
I don't know what dependency injection is yet, so I figure I'm not using it :)
Steve the Plant
If you are doing MVVM, you might want to investigate it. If your project is of any size, I'd also suggest looking at (As Steve Robbins rightly mentioned) Prism. It's a very good application of DI. Has a few things that make MVVM a bit easier. If you aren't at least using mvvmfoundation.codeplex.com you are working too hard :)
Anderson Imes
A: 

Acceptable, yes, but if you are using PRISM, or DI of any sort, then it would make more sense to resolve it from the container and then set the datacontext either in code, or using a markup extension, depending on your exact solution.

Steven Robbins
Heh... great minds think alike, eh?
Anderson Imes
I try not to answer any WPF/SL question without mentioning DI or PRISM somewhere ;-)
Steven Robbins
Ah... I was simply implying it. I love Prism... good idea to sell it.
Anderson Imes
A: 

If you want to use Dependency Injection (DI) in the View-First approach try ViewModel locator pattern:

public static class ViewModelLocator
{
  public static MainWindowViewModel MainWindowViewModel
  {
    get 
    {
      return ObjectFactory.GetInstance<MainWindowViewModel>(); 
    }
  }
};

and WPF code:

<Window 
    ...
    DataContext="{x:Static Services:ViewModelLocator.MainWindowViewModel}"
    >
Pawel Lesnikowski