我遇到一个数据网格问题,其中列是带有ContextMenu的文本框。但问题是,然后我右键单击文本框,未选中该行。这意味着它可以将值设置在错误的位置。在下面的图片中显示了问题。我右键单击了第一行,但它仍然选中了下面的行,这意味着如果我选择"混合油漆"它会将图片插入预期的行下方。
这是该列的代码:
<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>
答案 0 :(得分:1)
我找到了问题的解决方案:
在xaml代码中我添加了这个:
<DataGrid MouseRightButtonUp="UIElement_OnMouseRightButtonUp" Name="dataGrid1"></DataGrid>
代码背后:
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;
}
}