【问题标题】:How can I bind a ContextMenu inside a DataTemplate to the DataContext of the parent ListBox如何将 DataTemplate 中的 ContextMenu 绑定到父 ListBox 的 DataContext
【发布时间】:2011-04-28 20:07:21
【问题描述】:

我在 DataTemplate 中有一个 ContextMenu(来自 Silverlight 工具包),用作 ListBox 的 ItemTemplate:

<DataTemplate x:Key="BillItemDataTemplate">
  <Grid Margin="0,0,0,12" x:Name="ItemGrid">
    <kit:ContextMenuService.ContextMenu>
      <kit:ContextMenu>
        <kit:MenuItem Header="delete item" 
                      Command="{Binding ???????.DeleteItemCommand}"
                      CommandParameter="{Binding}" />
      </kit:ContextMenu>
    </kit:ContextMenuService.ContextMenu>
    [...]
  </Grid>
</DataTemplate>

如何告诉 ContextMenu.Command 绑定到由 outer DataContext 公开的视图模型上的属性(即应用于 ListBox 的属性)?如果我是对的,我不能按照here 的解释使用 WPF 相关声明。

如果我的子视图模型不需要引用“父”视图模型,我会更喜欢。

【问题讨论】:

    标签: xaml windows-phone-7 silverlight-3.0


    【解决方案1】:

    使用可以使用 ElementName 绑定。我这里没有代码,但你可以做类似的事情

    DataContext="{Binding ElementName=LayoutRoot,Path=DataContext}"
    

    其中 LayoutRoot 是 ListBox 之外的元素,或者是 ListBox 本身。

    【讨论】:

    • 我不想更改 MenuItem 的 DataContext,因为我将它用于 CommandParameter。我试过 Command="{Binding DataContext.DeleteItemCommand, ElementName=LayoutRoot}" 但还是不行。 SL3 和 WP7 有区别吗?
    • 我不确定为什么它不起作用说实话我已经使用上述问题来解决上下文菜单的这个确切问题。我要做的是从简单的开始,尝试 ListBox 元素名称,尝试在没有数据上下文的情况下查看哪个部分工作不正常。
    【解决方案2】:

    为了记录,我已经习惯在每个子视图模型上都有一个 ICommand 属性,在创建每个子视图模型时设置为父 ICommand,再次使用 CommandParameter="{Binding}"

    【讨论】:

      猜你喜欢
      • 2011-11-27
      • 2018-08-29
      • 1970-01-01
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      • 2012-08-23
      相关资源
      最近更新 更多