Sasha
Sasha

Reputation: 853

Datagrid CancelEdit doesn't work

My DataGrid is defined in XAML:

<datagrid:ThemedDataGrid AutoGenerateColumns="False" ItemsSource="{Binding Model.ItemCollection, UpdateSourceTrigger=PropertyChanged}"  
                 SelectionUnit="FullRow" SelectedItem="{Binding Model.DatagridSelectedItem, UpdateSourceTrigger=PropertyChanged}">
</datagrid:ThemedDataGrid>

I have an Event RowEditEnding where I check if in a column already exists a cell with the same value previously entered. If it exists, then I need to cancel edit. My RowEditEnding method is below:

int counter = 0;
Model.ItemCollection.ForEach(x =>
{
    //if column is not empty
    if (!String.IsNullOrEmpty(x.Name))
    {
        if (x.Name== Model.DatagridSelectedItem.Name)
        {
            counter++;
            if (counter > 1)
            {
                MessageBox.Show("Doubled Name");
                e.Cancel = true;
                datagrid.CancelEdit(DataGridEditingUnit.Row);                                                            
            }
        }
    }
});

The problem is this line:

datagrid.CancelEdit()

that doesn't change cell value to the previous one, and I get infinite loop. How can I solve it?

Upvotes: 2

Views: 5018

Answers (4)

Sir Jacob
Sir Jacob

Reputation: 55

I had the same issue. In my personal experience, replacing datagrid.CancelEdit(DataGridEditingUnit.Row); with datagrid.EndEdit(); did the trick.

Usage Example:

In the GIF below, I have applied the method .EndEdit() to the second column (nothing is applied to the first column). As you can see, the first column allows the cell to be edited (a typing cursor appears), while the second column does not.

EndEdit() Method Preventing Cel

Upvotes: 0

PPr
PPr

Reputation: 81

Implement IEditableObject Interface for your class.Which is a ObservableCollection.(Diagnostics is a class and Name is the property)

   private Diagnostics backupCopy;
   private bool inEdit;

   public void BeginEdit()
   {
       if (inEdit) return;
       inEdit = true;
       backupCopy = this.MemberwiseClone() as Diagnostics;
   }

   public void CancelEdit()
   {
       if (!inEdit) return;
       inEdit = false;
       this.Name= backupCopy.Name;
   }

   public void EndEdit()
   {
       if (!inEdit) return;
       inEdit = false;
       backupCopy = null;
   }

Upvotes: 0

Alberto Solano
Alberto Solano

Reputation: 8227

Is your collection bound to the ItemsSource property populated with custom objects? If so, I think your custom data class has to implement the IEditableObject interface. Indeed from the DataGrid documentation:

To guarantee that edits can be committed and canceled correctly, the objects in the DataGrid must implement the IEditableObject interface.

Upvotes: 4

Jan Rothkegel
Jan Rothkegel

Reputation: 762

Try to leave out this:

datagrid.CancelEdit(DataGridEditingUnit.Row);   

To my eyes, e.Cancel=true should do the job.

Upvotes: 1

Related Questions