Unfortunately, there is no easy way to do this in an MVVM
pattern as the necessary properties on DataGridCell
don't exist and edit mode in a DataGrid
can only be achieved by calling methods.
The way to minimise the nastiness of the solution is to implement an interface so that the code in your View
work against an interface rather than directly interacting with your ViewModel
, allowing at least for some level of decoupling. Attach the event handlers for your interface during your DataContextChanged
handler in your View
.
Ideally your interface should raise an event and you then handle that in the View code-behind to call BeginEdit()
on the DataGrid
once you've focused your specific cell. Focus the particular cell, start the edit, then focus the now created child editing element control (i.e. a TextBox
).
For example:
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
IRaiseStartCellEditEvent context = DataContext as IRaiseStartCellEditEvent;
if (context != null)
{
context.StartCellEdit += (o, args) =>
{
//Get the cell from first row
var cell = DataGrid.GetCell(0, 2);
//Focus on the cell for editing
cell.Focus();
//Start editing the cell
DataGrid.BeginEdit();
//Get the editing textbox
var tbEditor = Extensions.GetVisualChild<TextBox>(cell);
//Force the keyboard focus
if (tbEditor != null)
{
Keyboard.Focus(tbEditor);
tbEditor.SelectAll();
}
};
}
}
<DataGridTextColumn>
? Can you provide the code? – Felix Castor