I have a DataGrid where the user can only enter new rows using an add command bound to a view model. The attached behavior shown below activates the correct cell.
What I want to do now is effectively make the new row 'modal'. That is, I don't want the user to be able to do anything else with the grid until the new row is valid and committed, or the edit is cancelled.
Assuming my view model knows when it is valid and implements IEditableObject, can I get all of that out of my attached behavior? What must be done?
Cheers,
Berryl
code
public class NewItemAddedByCommandBehavior : Behavior<DataGrid>
{
private MainWindowViewModel _vm;
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.DataContextChanged += OnAssociatedObject_DataContextChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.DataContextChanged -= OnAssociatedObject_DataContextChanged;
_vm.NewItemAddedByCommand -= OnNewItemAddedByCommand;
}
private void OnAssociatedObject_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) {
_vm = (MainWindowViewModel) AssociatedObject.DataContext;
_vm.NewItemAddedByCommand += OnNewItemAddedByCommand;
}
private void OnNewItemAddedByCommand(object sender, EventArgs e)
{
var currentItem = _vm.SelectedItem;
var col = AssociatedObject.Columns[1];
AssociatedObject.CurrentCell = new DataGridCellInfo(currentItem, col);
AssociatedObject.ScrollIntoView(currentItem, col);
AssociatedObject.Focus();
AssociatedObject.BeginEdit();
}
}