Hi All
I have a Datagrid in a user control (changeable) that is hosted in a main window, I also have an "Add" buttun in the main window that adds a new row to the Datagrid of the current user control by adding an item to it's bound ObservableCollection. All this works fine, but I would like the first visible cell in the new row to go into edit mode once added. This is so the user can type in the new data without having to click twice on the new row as well as avoiding the ValidateOnDataErrors on the cell which tests for String.IsNullOrWhiteSpace() so returns an error on the newly created empty item.
After searching for ways to achieve this I decided the the DataGrid.BeginEdit() should do the job. The only issue was that the Add() method is bound to the Add button so resides in the Main Window ViewModel while I needed to use the DataGrid.BeginEdit() in the User Control View. I resolved this using the message system from MVVM Light.
In the Main Window ViewModel
public void Add() { SelectedWorkspace.AddItem(); Messages.AddNewItemMessage.Send("Position"); }
In the UseControl View
public void NewItemAdded(string type) { if (type == "Position") { PositionsList.SelectedIndex = PositionsList.Items.Count - 1; PositionsList.CurrentColumn = PositionsList.Columns[1]; // First visible cell PositionsList.BeginEdit(); PositionsList.Focus(); } }
In the User Control XAML
<DataGridTextColumn IsReadOnly="False" Header="Title" Binding="{Binding Path=Title, ValidatesOnDataErrors=True, Mode=TwoWay, NotifyOnTargetUpdated=True}" />
The new row is added as expected, the Focus is moved to the first visible cell in the new row or atleast appears to be, but it is not in edit mode and requires 2 clicks before it does so which sugests that the cell is not actually selected.
Thinking this may be caused by the render not being completed I tried
public void NewItemAdded(string type) { if (type == "Position") { Dispatcher.BeginInvoke((Action)delegate { PositionsList.SelectedIndex = PositionsList.Items.Count - 1; PositionsList.CurrentColumn = PositionsList.Columns[1]; // First visible cell bool _edit = PositionsList.BeginEdit(); PositionsList.Focus(); }, DispatcherPriority.ApplicationIdle, null); } }
With the same result. Also using the debugger I found that _edit is false meaning the BeginEdit has failed but I no idea why.
Any pointers would be apreciated.
Thanks in advance
Dan