I got some problems accessing a specific DataContext from within a Style.
I have a DataGrid defined like this:
<DataGrid Name="ReferenceDataGrid" ItemsSource="{Binding Items}" AutoGenerateColumns="False" RowHeaderWidth="0" IsReadOnly="True">
<DataGrid.Resources>
<Style TargetType="DataGridRow">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Delete" Command="???" />
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</DataGrid.Resources>
...
The DataContext property of the Page containing this DataGrid is set to
DataContext="{Binding RelativeSource={RelativeSource Self}}"
I want to bind a RelayCommand to the MenuItem and tried several different ways to do this:
Command="{Binding DeleteCommand}"Command="{Binding ElementName=Root, Path=DeleteCommand}"// Page element's name set to RootCommand="{Binding ElementName=Root, Path=DataContext.DeleteCommand}"Command="{Binding Path=DataContext.DeleteCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}}"
I set a breakpoint in the command handler of DeleteCommand but none of the variations above got there.
Let's say Items contains elements of type Foo.
If I define the command in Foo the handler gets triggered so it seems that whatever I've done above, the DataContext of each DataGridRow seems to be the list element itself.
Any idea what to do about it?
Edit:
I also tried to extract the DataContext into a separate class and reference this instead of Relative Self as I thought the list elements might use Relative Self as their DataContext instead of the Page instance it refers to. Unfortunately I was wrong.