I have an problem with a datagrid where a column is a Textbox with a ContextMenu. But the problem is that then i right click on the textbox the row is not selected. Which means that it can set the values in the wrong place. In the picture below it's shown'en the issue. I have right clicked the top row, but it's still the row below is selected, which means that if i select "Mixed Paint" it will like the picture be inserted below the intended row.
This is the code for the column:
<DataGridTemplateColumn Header="{wpfTx:Translate Action}" IsReadOnly="false" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Action, Mode=TwoWay}" TextWrapping="Wrap" BorderThickness="0" BorderBrush="Transparent">
<TextBox.ContextMenu>
<ContextMenu>
<MenuItem ItemsSource="{Binding ActionMenu}">
<MenuItem.Icon>
<controls:Icon IconKeyName="Config" Height="45" Width="45"/>
</MenuItem.Icon>
<MenuItem.Header >
<Label Content="Standard actions" VerticalContentAlignment="Center" FontSize="16" FontWeight="Bold"/>
</MenuItem.Header>
<MenuItem.ItemTemplate>
<DataTemplate>
<MenuItem Command="{Binding ActionMenuCommand}" CommandParameter="{Binding}">
<MenuItem.Header>
<Label Content="{Binding Description}" FontSize="16" FontWeight="Bold"/>
</MenuItem.Header>
<MenuItem.Icon>
<controls:Icon IconKeyName="Edited" Height="45" Width="45"/>
</MenuItem.Icon>
</MenuItem>
</DataTemplate>
</MenuItem.ItemTemplate>
</MenuItem>
</ContextMenu>
</TextBox.ContextMenu>
</TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
I found the solution to the problem:
In the xaml code i added this:
<DataGrid MouseRightButtonUp="UIElement_OnMouseRightButtonUp" Name="dataGrid1"></DataGrid>
And Code behind:
private void UIElement_OnMouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
var dep = (DependencyObject)e.OriginalSource;
while ((dep != null) && !(dep is DataGridCell))
{
dep = VisualTreeHelper.GetParent(dep);
}
if (dep == null) return;
if (dep is DataGridCell)
{
var cell = dep as DataGridCell;
cell.Focus();
while ((dep != null) && !(dep is DataGridRow))
{
dep = VisualTreeHelper.GetParent(dep);
}
var row = dep as DataGridRow;
dataGrid1.SelectedItem = row.DataContext;
}
}