【问题标题】:How to bind command into ContextMenu in DataTemplate如何将命令绑定到 DataTemplate 中的 ContextMenu
【发布时间】:2015-05-07 14:35:33
【问题描述】:

我对绑定有点迷茫。 在过去的一个小时里我尝试了很多东西,我无法一一列举。我对 DataTemplate 中的 contextMenu 有疑问。

解释一下:我有一个UserControl。它的 dataContext 就是它自己。在这个UserControl 中,我有一个ItemsControl 来表示一个超链接列表。我的ItemsControl itemsSource 已绑定(它由对象元素组成)。 我重新定义了ItemsControl.ItemTemplate。在内部,我创建了一个 HyperLink,以TextBlock 作为子级以使其工作,并在此TextBlock 上,通过执行以下操作设置ContextMenu

<TextBlock.ContextMenu>
  <ContextMenu DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}">
    <MenuItem Header="Enregistrer la pièce jointe" Foreground="Black">
      <MenuItem Header="Dans le dossier patient" Command="{Binding DataContext.SaveAttachmentIntPatientFolderCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" CommandParameter="{Binding FilePath}" Foreground="Black" />
      <MenuItem Header="Enregistrer sous ..." Command="{Binding DataContext.SaveAttachmentAsCommand}" CommandParameter="{Binding FilePath}" Foreground="Black" />
    </MenuItem>
  </ContextMenu>
</TextBlock.ContextMenu>

所以我有

UserControl --> ItemsControl --> ItemTemplate --> HyperLink --> TextBlock --> ContextMenu --> ContextMenuItem

我知道我的第一个相对来源不起作用,我遇到了绑定错误。我想要的是绑定我的 UserContorl 数据上下文,它有这些命令。

我该如何继续?

谢谢

【问题讨论】:

    标签: c# wpf binding


    【解决方案1】:

    ContextMenu 采用 ItemsControl 的 DataContext,因此它不能直接访问 ViewModel。此外,它不是 VisualTree 的一部分,因此您不能进行 RelativeSource 绑定。所以我们需要通过TextBlock的Tag属性获取UserControl的DataContext,然后绑定到ContextMenu。 你参考下面的代码。

    <TextBlock Text="{Binding }" Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType=UserControl}}">
      <TextBlock.ContextMenu>
        <ContextMenu >
          <MenuItem Header="Enregistrer la pièce jointe" Foreground="Black">
            <MenuItem Header="Dans le dossier patient" 
                      Command="{Binding Path=PlacementTarget.Tag.SaveAttachmentIntPatientFolderCommand,
                                RelativeSource={RelativeSource AncestorType=ContextMenu}}"                                                  
                      Foreground="Black" />
            <MenuItem Header="Enregistrer sous ..." 
                      Command="{Binding Path=PlacementTarget.Tag.SaveAttachmentAsCommand,
                                RelativeSource={RelativeSource AncestorType=ContextMenu}}"  
                      Foreground="Black" />
          </MenuItem>
        </ContextMenu>
      </TextBlock.ContextMenu>
    </TextBlock>     
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-10
      • 2016-07-02
      • 1970-01-01
      • 1970-01-01
      • 2011-04-04
      • 2011-05-11
      • 1970-01-01
      相关资源
      最近更新 更多