I have a common task. Implement CheckBox checking in DataGrid by one-click. I deside make a DataGridExtended class, derived from DataGrid, and implement something like that:
XAML:
<DataGrid x:Class="DataGrid.DataGridExtended"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
</DataGrid>
CODE:
public partial class DataGridExtended : System.Windows.Controls.DataGrid
{
private int _oldRowIndex;
private int _oldColumnIndex;
public DataGridExtended()
{
MouseLeftButtonUp += DataGridExtendedMouseLeftButtonUp;
MouseLeftButtonDown += DataGridExtendedMouseLeftButtonDown;
}
private void DataGridExtendedMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// Если сендер реально DataGridExtended
var dataGridExt = sender as DataGridExtended;
if (dataGridExt == null)
return;
// Получаем текущую ячейку
var currentCell = dataGridExt.CurrentCell;
_oldRowIndex = dataGridExt.SelectedIndex;
_oldColumnIndex = dataGridExt.CurrentColumn.DisplayIndex;
}
private void DataGridExtendedMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
// Если сендер реально DataGridExtended
var dataGridExt = sender as DataGridExtended;
if (dataGridExt == null)
return;
var rowIndex = dataGridExt.SelectedIndex;
var columnIndex = dataGridExt.CurrentColumn.DisplayIndex;
// Получаем текущую ячейку
var currentCell = dataGridExt.CurrentCell;
//if (_oldRowIndex != rowIndex || _oldColumnIndex != columnIndex)
// return;
// Получаем текущую колонку
var currentColumn = currentCell.Column;
// Получаем контент текущей ячейки
var cellContent = currentColumn.GetCellContent(currentCell.Item);
// Если кликнули по чекбоксу
var checkBox = cellContent as CheckBox;
if (checkBox == null)
return;
// Ставием его в фокус
checkBox.Focus();
// Меняем чек на противоположный
checkBox.IsChecked = !checkBox.IsChecked;
// Получаем выражение привязки для чекбокса
var bindingExpression = checkBox.GetBindingExpression(ToggleButton.IsCheckedProperty);
// Если привязка есть - обновляем ее
if (bindingExpression != null)
bindingExpression.UpdateSource();
}
}
DataGridExtendedMouseLeftButtonUp handler works fine, but DataGridExtendedMouseLeftButtonDown doesn't firing. And that is the problem.
Without DataGridExtendedMouseLeftButtonDown invoking, checking behaviour is not what I want. Namely, checking is working even I move cursor out from grid :E Trying to use PreviewMouseLeftButtonDown instead MouseLeftButtonDown give wrong effect :(
So, how can I solve my problem? Don't offer use different approaches to implement one-click checking plz :) Like using XAML-style for example...