I struggle to bind to an ICommand in a place described in the title.
Firstly, my DataContext in this place is a Item
and not my ViewModel, so I need to get around this somehow. I already did this on my ItemClickCommand, but the same solution will not work, because:
Secondly, a ContextMenu is not part of the window, and not part of the visual or logical tree. What woodoo I need to implement to get around this, I do not know.
ViewModel:
public ICommand CopyTextCommand { get; private set; }
public Constructor()
{
CopyTextCommand = new RelayCommand(InsertToClopboard);
Initialize();
}
private void InsertToClopboard(object parameter)
{
// Want to get in here.
}
View:
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ListView Grid.Row="0" x:Name="MainListView" ItemsSource="{Binding Items}" Background="Transparent" BorderBrush="Transparent" Margin="0" HorizontalContentAlignment="Stretch">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="0" Visibility="{Binding GuiVisibility, Converter={StaticResource BoolToVisibility}}">
<Grid.InputBindings>
<MouseBinding Gesture="LeftClick"
Command="{Binding Path=DataContext.ItemClickCommand, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}"
CommandParameter="{Binding}"/>
</Grid.InputBindings>
<Label ...
Content="{Binding PNR}" >
<Label.ContextMenu>
<ContextMenu>
<MenuItem
Name="MenuItemPnr"
Header="Copy"
Command="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget.DataContext}" <--This does not work-->
CommandParameter="test" />
</ContextMenu>
</Label.ContextMenu>
</Label>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
EDIT:
I have tried to add a Tag with the correct binding multiple places in en xaml, but the PlacementTarget of the MenuItem
is the ContextMenu
. And the ContextMenu does not know the correct DataContext. How do I get around this?