2

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();
    }
}
Berryl
  • 12,471
  • 22
  • 98
  • 182

2 Answers2

1

This post gave me a clue how to do this, roughly:

  1. Add an IsReadOnly property to the bound view model item
  2. Add an IsNew property to the bound view model item
  3. In the vm, before actually adding the item, set all existing items IsReadOnly = true
  4. when the newly added item is edited or its edit canceled, set IsReadOnly for all items back to false
  5. Modify the behavior similar to the posting answer (which oddly enough was not the accepted answer) but without the ReadOnlyService
  6. Style the DataGridRow

the payoff

enter image description here

enter image description here

Community
  • 1
  • 1
Berryl
  • 12,471
  • 22
  • 98
  • 182
1
<DataGrid.RowStyle>
    <Style TargetType="{x:Type DataGridRow}">
        <Setter Property="IsEnabled" Value="{Binding IsEnabled}"/>
    </Style>
</DataGrid.RowStyle>
Konstantin S.
  • 1,307
  • 14
  • 19
  • 2
    It is not recommended to post code-only answers, answers should provide more explanation about the code to make it the answer more useful and are more likely to attract upvotes [**From Review**](https://stackoverflow.com/review/low-quality-posts/29450927) – B001ᛦ Jul 26 '21 at 17:40