tags:

views:

16

answers:

2

The beginner tutorial I've followed said I should create a namespace on the window,

<Window ... xmlns:vm="clr-namespace:MyApp.ViewModels" />

And then set the DataContext like this,

<Window.DataContext>
    <vm:MyViewModel />
</Window.DataContext>

But I don't want the DataContext to apply to the whole window. I want different elements to use different contexts.

My DataGrid is defined like,

 <DataGrid ... DataContext="{Binding}" ItemsSource="{Binding Path=Queue}"

I guess that DataContext="{Binding}" bit basically uses "use parent context", but couldn't I set it to vm:MyViewModel right in there? I'm not sure of the proper syntax and the Visual Studio Properties window seems pretty useless in the matter.

+1  A: 

You can do it like:

<DataGrid ... ItemsSource="{Binding Path=Queue}">
    <DataGrid.DataContext>
          <mv:MyViewModel />
    </DataGrid.DataContext>
</DataGrid>

This is effectively the same way you set it on a Window.

Reed Copsey
Simple enough... I think I was confusing issues. Thanks!
Mark
+1  A: 

You can set the datacontext on the control itself. In the case of a DataGrid you'd use

        <DataGrid.DataContext>
              <vm:MyViewModel />
        </DataGrid.DataContext>
mdm20