简体   繁体   中英

WPF Context Menu won't Bind To VIewModel property

I am having a WPF binding issue that I cannot figure out. I have a ContextMenu template that is formatted as shown:

<ContextMenu x:Key="CopyPasteContextMenu">
    <MenuItem Header="AlternateDelete"
              Command="{Binding Path=PlacementTarget.Tag.DataContext.AlternateDeleteCommand, 
              RelativeSource={RelativeSource Self}, Mode=OneWay}"/>
</ContextMenu>

The context menu is being used in the DataTemplat, and the binding for the Tag on the Border is finding the PropertyEditorView correctly, I just can't get it from the border to the contextmenu.

<DataTemplate x:Key="PropertyValueCellViewingTemplate" DataType="viewModels:IConfigurationItemViewModel">
    <Border x:Name="ValueCellBorder"
           Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type views:PropertyEditorView}}}"
           ContextMenu="{StaticResource CopyPasteContextMenu}"
           Style="{StaticResource PropertyGridValueCellBorderStyle}">
        (...)
    </Border>
</DataTemplate>

The tag can bind properly to my view model which is called “PropertyEditorViewModel”. I can see this while debugging the system in the visual tree. When I drill into my Context Menu, the binding is not happening properly.

For my Command to work, I need it to bind properly to the Command to PropertyEditorView view model command called “AlternateDeleteCommand”.

public class PropertyEditorViewModel : DisposableViewModelBase, IPropertyEditorViewModel
{
    public ICommand AlternateDeleteCommand { get; set; }

Looked at this for a day so far, and not sure why my binding isn't working on the context menu, anyone got something I'm missing?

Thanks!

Doesn't the relative source need to be on the context menu and not on the menu item? Since you are checking the placement target of the context menu?

<MenuItem Header="AlternateDelete"
          Command="{Binding Path=PlacementTarget.Tag.DataContext.AlternateDeleteCommand, 
          RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Mode=OneWay}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM