开发者

How to set DataContext for a single element?

开发者 https://www.devze.com 2023-01-21 13:59 出处:网络
The beginner tutorial I\'ve followed said I should create a namespace on the window, <Window ... xmlns:vm=\"clr-namespace:MyApp.ViewModels\" />

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.开发者_JS百科 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.


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.


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

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

精彩评论

暂无评论...
验证码 换一张
取 消