且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将命令绑定到 DataTemplate 中的 ContextMenu

更新时间:2022-06-20 02:52:46

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

ContextMenu takes the DataContext of the ItemsControl and so it cannot access the ViewModel directly. Also It is not part of the VisualTree and so you cannot do RelativeSource binding. So We need to get the DataContext of the UserControl through TextBlock's Tag property and then bind to ContextMenu. You refer the below code.

<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>