WPF DataGrid PreviewMouseDown未按预期处理右键单击

Mat*_*rew 5 c# wpf datagrid mouseevent

我在User Control中设置了一个带有PreviewMouseDown事件的DataGrid.这个想法是当用户将鼠标移动到单元格时,它会根据单元格的内容设置要运行的Action,并且无论使用哪个鼠标按钮,Action都会在用户单击时运行.
我的事件处理程序(C#):

private void LadderMouseClick(object sender, System.Windows.Input.MouseButtonEventArgs e)  {
        if (m_ActiveAction != null) {
            m_ActiveAction();
        }
        e.Handled = true;
    }
Run Code Online (Sandbox Code Playgroud)

我的DataGrid(XAML):

<DataGrid AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" CanUserReorderColumns="False" CanUserResizeColumns="False" CanUserSortColumns="False"  EnableRowVirtualization="True"  ItemsSource="{Binding Source={StaticResource sourceCollection}}" Name="DataGrid" RowDetailsVisibilityMode="Collapsed" IsReadOnly="True" Height="600" MouseLeave="DataGrid_MouseLeave" MouseEnter="DataGrid_MouseEnter" PreviewMouseDown="LadderMouseClick" PreviewMouseDoubleClick="LadderMouseDoubleClick" VerticalScrollBarVisibility="Hidden" SelectionUnit="Cell" SelectionMode="Single">
Run Code Online (Sandbox Code Playgroud)

这可以正常运行,当用户右键或左键单击DataGrid时,可以正常运行该操作.然而,问题在于,当用户右键单击时,他们的鼠标所在的单元格会被选中(单元格周围会出现黑色边框); 当他们左键单击时不会发生这种情况.

他们为什么表现不同?它们不应该以同样的方式处理吗?有什么东西真的很简单吗?

提前致谢!

编辑:
我到目前为止尝试过DataGrid.UnselectAll(),DataGrid.UnselectAllCells(),DataGrid.SelectedIndex = -1,以及DataGrid.CurrentCell = default(DataGridCellInfo).他们都没有为我工作.

编辑#2:
如果有帮助,我正在使用带有TextBlocks的DataGridTemplateColumns来显示我的数据.这会导致这种行为吗?

解决方案:
这是由Peter Hansen的建议解决的,即将一个PreviewMouseRightButtonDown事件添加到DataGrid以及PreviewMouseDown事件.

Pet*_*sen 5

我想你看到的是单元格的边框,当它有焦点时就会显示出来。

您可以通过将其厚度设置为 0 来删除它,如下所示:

<DataGrid.CellStyle>
    <Style TargetType="DataGridCell">
        <Setter Property="BorderThickness" Value="0" />
    </Style>
</DataGrid.CellStyle>
Run Code Online (Sandbox Code Playgroud)

更新:
显然,当您设置PreviewMouseDown要处理的事件时,DataGrid 只会在您使用鼠标左键时停止选择单元格。

您还必须处理PreviewMouseRightButtonUp以阻止右键单击选择单元格。

我认为这会解决你的问题?