I have implemented IEditableObject
for my ViewModel and the below controls are bound to it.
Now when the first time I fire up the Window
containing these controls, the BeginEdit()
method runs and backs up the variables.
My problem is this: When I start editing the DataGrid
again the BeginEdit()
method runs and saves the changes to my already backed up variables! This ruins the purpose of the BeginEdit()
and CancelEdit()
. Now if I choose to cancel the Window, I won't have the original data. How can I prevent this?
<ComboBox ItemsSource="{Binding Path=CoatingFactors}"
SelectedItem="{Binding Path=CoatingFactor}">
</ComboBox>
<DataGrid ItemsSource="{Binding Path=CustomCFactors}"
....
</DataGrid>
Here is how I have implemented the BeginEdit()
and CancelEdit()
methods:
private List<CustomCFactorItem> customCFactors_ORIGINAL;
private double coatingFactor_ORIGINAL;
public void BeginEdit()
{
customCFactors_ORIGINAL = customCFactors.ConvertAll(o => o.Clone()).ToList();
coatingFactor_ORIGINAL = coatingFactor;
}
public void CancelEdit()
{
customCFactors = customCFactors_ORIGINAL.ConvertAll(o => o.Clone()).ToList();
coatingFactor = coatingFactor_ORIGINAL;
}
UPDATE:
For now, I'm using a little hack like this:
private List<CustomCFactorItem> customCFactors_ORIGINAL;
private double coatingFactor_ORIGINAL;
private int editNum = 0;
public void BeginEdit()
{
if (editNum > 0) return;
editNum++;
customCFactors_ORIGINAL = customCFactors.ConvertAll(o => o.Clone());
coatingFactor_ORIGINAL = coatingFactor;
}
public void EndEdit()
{
editNum = 0;
}
public void CancelEdit()
{
editNum = 0;
customCFactors = customCFactors_ORIGINAL.ConvertAll(o => o.Clone());
coatingFactor = coatingFactor_ORIGINAL;
}
It's best not to fight with the WPF
DataGrid
control at the UI layer. Without writing your own controls designed to suit your own purposes, you simply won't win that fight. There will always be another Microsoft "gotcha" to deal with. I recommend implementing the desired behaviour from the safe-haven of anObservableCollection
.And Here's a sample of what
CustomCFactorItem
might look likeAnd this is a simple View that binds the collection to
DataGrid
. Notice that output is written to the console each time an edit is made.