Skip to content

Commit

Permalink
fix: DataGrid selection should now properly select item
Browse files Browse the repository at this point in the history
This should now both have the click to edit and the selection. 
Fixes #2363
  • Loading branch information
punker76 committed Jan 13, 2023
1 parent 5ea3819 commit a977760
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions src/MahApps.Metro/Controls/Helper/DataGridHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -522,9 +522,9 @@ private static void EnableCellEditAssistPropertyChangedCallback(DependencyObject
/// <summary>
/// Allows editing of components inside of a <see cref="DataGrid"/> cell with a single left click.
/// </summary>
private static void DataGridOnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
private static void DataGridOnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs mouseArgs)
{
var originalSource = (DependencyObject)e.OriginalSource;
var originalSource = (DependencyObject)mouseArgs.OriginalSource;
var dataGridCell = originalSource
.GetVisualAncestry()
.OfType<DataGridCell>()
Expand All @@ -542,7 +542,7 @@ private static void DataGridOnPreviewMouseLeftButtonDown(object sender, MouseBut
var dataGrid = (DataGrid)sender;

// Check if the cursor actually hit the element and not just the complete cell
var mousePosition = e.GetPosition(element);
var mousePosition = mouseArgs.GetPosition(element);
var elementHitBox = new Rect(element.RenderSize);
if (elementHitBox.Contains(mousePosition))
{
Expand All @@ -556,13 +556,22 @@ private static void DataGridOnPreviewMouseLeftButtonDown(object sender, MouseBut
dataGrid.CurrentCell = new DataGridCellInfo(dataGridCell);
dataGrid.BeginEdit();

// Begin edit likely changes the visual tree, trigger the mouse down event to cause the DataGrid to adjust selection
var mouseDownEvent = new MouseButtonEventArgs(mouseArgs.MouseDevice, mouseArgs.Timestamp, mouseArgs.ChangedButton)
{
RoutedEvent = Mouse.MouseDownEvent,
Source = mouseArgs.Source
};

dataGridCell.RaiseEvent(mouseDownEvent);

// Now use the content from the editable template/style
switch (dataGridCell.Content)
{
// Send a 'left click' routed command to the toggleButton
case ToggleButton toggleButton:
{
var newMouseEvent = new MouseButtonEventArgs(e.MouseDevice, 0, MouseButton.Left)
var newMouseEvent = new MouseButtonEventArgs(mouseArgs.MouseDevice, 0, MouseButton.Left)
{
RoutedEvent = Mouse.MouseDownEvent,
Source = dataGrid
Expand All @@ -576,7 +585,7 @@ private static void DataGridOnPreviewMouseLeftButtonDown(object sender, MouseBut
case ComboBox comboBox:
{
comboBox.IsDropDownOpen = true;
e.Handled = true;
mouseArgs.Handled = true;
break;
}
}
Expand Down

0 comments on commit a977760

Please sign in to comment.