Silverlight - Access the Layout Grid's DataContext in a DataGrid CellTemplate's DataTemplate?

南笙酒味 提交于 2019-12-08 06:11:11

问题


I am using Silverlight 3 to develop an application. In my app, I have a layout Grid (named "LayoutGrid") in which I have a DataGrid (named "PART_datagrid") with DataGridTemplateColumns. The LayoutGrid is set a DataContext in which there is a Ladders list as a property. This Ladders list is set as the ItemsSource for the PART_datagrid.

<Grid x:Name="LayoutRoot">
   <DataGrid x:Name="PART_datagrid" ItemsSource="{Binding Ladders}">
      ...
      <DataGridTemplateColumn>
         <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
               <Button Name="DeleteLadder" Click.Command="{Binding ElementName=LayoutRoot, Path=DataContext.DeleteLadderCommand}" />

Now in one of the DataGridTemplateColumns I have a button which should invoke a Command thats present in the LayoutGrid's DataContext. So I tried Element-To-Element binding on my DataTemplate button as follows

<Button Name="DeleteLadder" Click.Command="{Binding ElementName=LayoutRoot, Path=DataContext.DeleteLadderCommand}" />

But this does not seem to work. What I want to achieve is to handle the event of deletion of a DataGrid row at the parent DataContext level using the command.

Can someone pls suggest how do I proceed on this?

Thanks in advance...


回答1:


The problem seems to be that each row uses the datagrid source as its "new" datacontext kind of thing. So from each row you need to get out of the grid and point to someting higher in the hierarchy to get the parent datacontext. These solutions may help. Solution 2 worked for me when I encountered the same problem.

Solution 1 using the Locator

See this posting: Silverlight DataGrid.Celltemplate Binding to ViewModel

Solution 2 using define resource at the top and hooking up to its datacontext.

<UserControl.Resources>
    <ContentControl x:Key="cc1" Content="{Binding}" />
</UserControl.Resources>

then use something like this inside your datagrid

Command="{Binding Source={StaticResource cc1}, Path=Content.DeleteLadderCommand}"

Good Luck



来源:https://stackoverflow.com/questions/2425995/silverlight-access-the-layout-grids-datacontext-in-a-datagrid-celltemplates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!