views:

976

answers:

2

I"m trying to wrap my head around MVVM. I understand a lot of it, but I'm having difficulty grasping one aspect: Setting DataContext.

I want to show an view with a particular object. The user doesn't get to decide what is visible, so I need to create the view in code. Then, I want to set the DataContext of the view to an object (for binding). I'm trying not to put code in the View for this, but View.LayoutRoot.DataContext isn't public.

What am I missing?

trying to avoid this:

public class View
{
    public View(object dataContext)
    {
        InitializeComponent();
        LayoutRoot.DataContext = dataContext;  
    }
}

with something like this:

public class ViewModel
{
    ...

    public UIElement GetView()
    {
        UIElement *element = new View();
        element.LayoutRoot.DataContext = element;
        return element;
    }
}
+5  A: 

Don't forget that the View should know about the ViewModel, and not the other way around.

So in your case puting code in the ViewModel to create the view isn't the best way around.

Josh Smith's article on MVVM has a section on applying the View to the ViewModel. He recommends using WPF's DataTemplates to select your View in XAML.

Cameron MacFarland
thanks a bunch for your help. it pushed me in the right direction.
Jeremiah
A: 

If you use a XAML control or Window (which should be the case if you use MVVM), LayoutRoot (Grid by default) is public. In your example, you use just a plain class for View, so it is hard to tell what is going on.

Also, I second Cameron's opinion - nor View or ModelView should deal with assigning DataContext. It can be done in different ways (DataTemplate, dependency injection, special builder class, plain code) but normally it happens on the application level.

Sergey Aldoukhov