I have a UserControl with a DataGrid in it. The columns of the DataGrid do I create as DataGridTemplateColumns. The DataGrid looks something like:
<DataGrid Grid.Row="1" Style="{StaticResource DataGridStyle}" Margin="5"
ItemsSource="{Binding Storage.Items, UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
MaxHeight="400" VerticalAlignment="Top">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Comment" Width="*" SortMemberPath="Comment">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Comment}" Margin="3,2" VerticalAlignment="Center"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
// several more column-definitions
<DataGridTemplateColumn Header="Actions" Width="90">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Margin="5" Content="Action..." Cursor="Hand" >
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<TextBlock TextDecorations="Underline" HorizontalAlignment="Center" Foreground="Blue">
<ContentPresenter/>
</TextBlock>
</ControlTemplate>
</Button.Template>
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<EventTrigger RoutedEvent="Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="ContextMenu.IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Style.Triggers>
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Edit"/>
<MenuItem Header="Delete" Command="{Binding DataContext.CommonCommand,
RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}"
CommandParameter="{x:Static defs:CommonCommandTarget.Delete}"/>
<Separator/>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>+
</DataGrid.Columns>
</DataGrid>
My problem is the binding of the Delete-Command of the ContextMenu in the last column. The contextmenu is shown but on a click nothing happens.
In the output I can see a binding-error:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', AncestorLevel='1''. BindingExpression:Path=DataContext.CommonCommand; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'Command' (type 'ICommand')
Outside the DataGrid or a Button directly in the Template-Column just works fine with the binding. so the Command is correctly.
What Ancestor or RelativeSource or whatever do I have to provide that my Command in the ViewModel will be called?