How to bind command into ContextMenu in DataTemplate

后端 未结 1 1656
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 03:26

I\'m a little bit lost with bindings. I tried so many things in the last hour, I cannot enumerate all of them. I have an issue with a contextMenu inside a DataTemplate.

相关标签:
1条回答
  • 2020-12-07 03:50

    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>     
    
    0 讨论(0)
提交回复
热议问题