【问题标题】:Silverlight - Access the Layout Grid's DataContext in a DataGrid CellTemplate's DataTemplate?Silverlight - 在 DataGrid CellTemplate 的 DataTemplate 中访问布局网格的 DataContext?
【发布时间】:2011-01-26 10:16:22
【问题描述】:

我正在使用 Silverlight 3 开发应用程序。在我的应用程序中,我有一个布局网格(名为“LayoutGrid”),其中有一个带有 DataGridTemplateColumns 的 DataGrid(名为“PART_datagrid”)。 LayoutGrid 设置了一个 DataContext,其中有一个 Ladders 列表作为属性。此梯形图列表设置为 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 中存在的命令。所以我在我的 DataTemplate 按钮上尝试了 Element-To-Element 绑定,如下所示

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

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

有人可以建议我如何进行此操作吗?

提前谢谢...

【问题讨论】:

  • 它“似乎不起作用”的方式是什么?
  • 你在使用 MVVM 框架吗?
  • 是的,我正在使用 MVVM 框架。我附加到按钮的 Click 命令(称为 DeleteCommand)的命令不会被调用。因此我说它不起作用。在我看来,LayoutRoot 的 DataContext 没有传递给 DataTemplate,因此按钮的绑定可能不起作用。

标签: silverlight-3.0 datagrid binding datatemplate celltemplate


【解决方案1】:

问题似乎是每一行都使用数据网格源作为它的“新”数据上下文类型的东西。因此,您需要从每一行中跳出网格并指向层次结构中更高的位置以获取父数据上下文。这些解决方案可能会有所帮助。当我遇到同样的问题时,解决方案 2 对我有用。

使用定位器的解决方案 1

看到这个帖子: Silverlight DataGrid.Celltemplate Binding to ViewModel

解决方案 2 在顶部使用定义资源并连接到其数据上下文。

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

然后在你的数据网格中使用类似的东西

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

祝你好运

【讨论】:

    猜你喜欢
    • 2016-01-19
    • 1970-01-01
    • 2013-12-04
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2011-11-29
    相关资源
    最近更新 更多