簡體   English   中英

如何將命令綁定到 DataTemplate 中的 ContextMenu

[英]How to bind command into ContextMenu in DataTemplate

我對綁定有點迷茫。 在過去的一個小時里我嘗試了很多東西,我無法一一列舉。 我在 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 數據上下文,它有這些命令。

我該如何繼續?

謝謝

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>     

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM