I have a WPF DataGrid and I'm trying to handle a scenario where an item does not exist in my ViewModel. When this happens, I display an error message and attempt to set focus back to the DataGrid cell to allow the user to edit the cell again. The issue is that while it stays on the cell that triggered the error, it doesn't select the entire content of the cell. Here's my code:
if (!_viewModel.ItemExists(codPro))
{
MessageBox.Show(
"O item não existe na tabela de itens.",
"Erro",
MessageBoxButton.OK,
MessageBoxImage.Error
);
e.Cancel = true;
(sender as DataGrid).Dispatcher.BeginInvoke((Action)(() =>
{
var dataGrid = sender as DataGrid;
if (dataGrid != null)
{
dataGrid.SelectedCells.Clear();
dataGrid.SelectedCells.Add(new DataGridCellInfo(e.Row.Item, e.Column));
dataGrid.CurrentCell = new DataGridCellInfo(e.Row.Item, e.Column);
dataGrid.BeginEdit();
var cellContent = dataGrid.Columns[e.Column.DisplayIndex].GetCellContent(e.Row);
if (cellContent != null)
{
var cell = cellContent.Parent as DataGridCell;
if (cell != null)
{
cell.Focus();
var textBox = cellContent as TextBox;
if (textBox != null)
{
textBox.SelectAll();
}
}
}
}
}));
return;
}
What am I missing or doing wrong that prevents the entire content of the cell from being selected?
I have a WPF DataGrid and I'm trying to handle a scenario where an item does not exist in my ViewModel. When this happens, I display an error message and attempt to set focus back to the DataGrid cell to allow the user to edit the cell again. The issue is that while it stays on the cell that triggered the error, it doesn't select the entire content of the cell. Here's my code:
if (!_viewModel.ItemExists(codPro))
{
MessageBox.Show(
"O item não existe na tabela de itens.",
"Erro",
MessageBoxButton.OK,
MessageBoxImage.Error
);
e.Cancel = true;
(sender as DataGrid).Dispatcher.BeginInvoke((Action)(() =>
{
var dataGrid = sender as DataGrid;
if (dataGrid != null)
{
dataGrid.SelectedCells.Clear();
dataGrid.SelectedCells.Add(new DataGridCellInfo(e.Row.Item, e.Column));
dataGrid.CurrentCell = new DataGridCellInfo(e.Row.Item, e.Column);
dataGrid.BeginEdit();
var cellContent = dataGrid.Columns[e.Column.DisplayIndex].GetCellContent(e.Row);
if (cellContent != null)
{
var cell = cellContent.Parent as DataGridCell;
if (cell != null)
{
cell.Focus();
var textBox = cellContent as TextBox;
if (textBox != null)
{
textBox.SelectAll();
}
}
}
}
}));
return;
}
What am I missing or doing wrong that prevents the entire content of the cell from being selected?
I managed to fix it by adding a line of code. I think I'm very dumb.
var cell = cellContent.Parent as DataGridCell;
if (cell != null)
{
cell.Focus();
var textBox = cellContent as TextBox;
if (textBox != null)
{
textBox.SelectAll();
textBox.Focus(); // this line
}
}