How to prevent adding an item to a DataGrid?

My problem

I am trying to prevent the user from adding blank lines DataGridwhen using the built-in .NET DataGridAddNewItem functionality. Therefore, when the user tries to complete the AddNew transaction DataGridand leaves it PageItemViewModel.Textempty, it should disappear from DataGrid.

The code

ViewModels

public class PageItemViewModel
{
    public string Text { get; set; }
}

public class PageViewModel
{
    public ObservableCollection<PageItemViewModel> PageItems { get; } = new ObservableCollection<PageItemViewModel>();
}

View

<DataGrid AutoGenerateColumns="True"
          CanUserAddRows="True"
          ItemsSource="{Binding PageItems}" />

I've already tried

... deleting an automatically created object from during processing:DataGrid ItemsSource

... but always get exceptions, such as:

  • System.InvalidOperationException: "Deletion" is not allowed during an AddNew or EditItem transaction. "
  • " System.InvalidOperationException: Unable to change ObservableCollection during CollectionChanged event.
  • System.InvalidOperationException: ItemsSource. ItemsControl.ItemsSource. "

PageItemViewModel ObservableCollection<PageItemViewModel>, ( : String.IsNullOrWhiteSpace(PageItemViewModel.Text) == true.


EDIT:

@picnic8: AddingNewItem RoutedEventArgs , , Handled. AddingNewItemEventArgs. .

private void DataGrid_AddingNewItem(object sender, AddingNewItemEventArgs e)
{
    var viewModel = (PageItemViewModel)e.NewItem;
    bool cancelAddingNewItem = String.IsNullOrWhiteSpace(viewModel.Text) == true;
    // ??? How can i actually stop it from here?
}
+4
2

, , , DataGrid PageItemViewModel, .

, , DataGrid.RowEditEnding , DataGridRowEditEndingEventArgs.EditAction DataGridEditAction.Commit DataGrid.CancelEdit, ( ), .

private void DataGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
    if (e.EditAction == DataGridEditAction.Commit)
    {
        var bindingGroup = e.Row.BindingGroup;
        if (bindingGroup != null && bindingGroup.CommitEdit())
        {
            var item = (PageItemViewModel)e.Row.Item;
            if (string.IsNullOrWhiteSpace(item.Text))
            {
                e.Cancel = true;
                ((DataGrid)sender).CancelEdit();
            }
        }
    }
}

, RowEditEnding , , . BindingGroup.CommitEdit .

+4

AddingNewItem . , .

var datagrid.AddingNewItem += HandleOnAddingNewItem;

public void HandleOnAddingNewItem(object sender, RoutedEventArgs e)
{
    if(myConditionIsTrue)
    {
        e.Handled = true; // This will stop the bubbling/tunneling of the event
    }
}
-1

Source: https://habr.com/ru/post/1691130/


All Articles