Silverlight - 在DataGrid CellTemplate的DataTemplate中访问Layout Grid的DataContext?

时间:2010-03-11 15:03:08

标签: silverlight-3.0 datagrid binding datatemplate celltemplate

我正在使用Silverlight 3来开发应用程序。在我的应用程序中,我有一个布局网格(名为“LayoutGrid”),其中我有一个带DataGridTemplateColumns的DataGrid(名为“PART_datagrid”)。 LayoutGrid设置为DataContext,其中有一个梯形图列表作为属性。此梯形图列表设置为PART_datagrid的ItemsSource。

<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}" />

现在在一个DataGridTemplateColumns中我有一个按钮,它应该调用LayoutGrid的DataContext中存在的Command。所以我在DataTemplate按钮上尝试了Element-To-Element绑定,如下所示

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

但这似乎不起作用。我想要实现的是使用该命令处理在父DataContext级别删除DataGrid行的事件。

有人可以建议我如何处理这个问题?

提前致谢...

1 个答案:

答案 0 :(得分:2)

问题似乎是每行使用datagrid源作为其“新”datacontext类的东西。因此,从每一行中,您需要离开网格并指向层次结构中较高的位置以获取父datacontext。这些方案可能有所帮助当遇到同样的问题时,解决方案2对我有用。

解决方案1使用定位器

查看此帖子:    Silverlight DataGrid.Celltemplate Binding to ViewModel

解决方案2使用顶部的define资源并连接到其datacontext。

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

然后在datagrid中使用类似的东西

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

祝你好运