Introducing EditableCollection

In the lasts lines of this post I talk about a Collection type that implements IEditableObject interface.
Let’s start with a simple interface:

public interface IEditableCollection<T> : 
IEnumerable<T>, IEditableObject, INotifyCollectionChanged {}

As you can see the interface also inherits INotifyCollectionChanged this is very usefull in data binding scenarios.
This is the implementation:

public class EditableCollection<T> : ObservableCollection<T>, IEditableCollection<T>
{
    private IList<T> _bakupList;
    private bool _isInEditMode;

    #region IEditableCollection Members

    public void BeginEdit()
    {
        _bakupList = new List<T>();
        Items.ForEach(_bakupList.Add);
        _isInEditMode = true;
    }

    public void EndEdit()
    {
        if (!_isInEditMode)
            throw new InvalidOperationException("EndEdit without a BeginEdit"); 
        _isInEditMode = false;
        _bakupList = null;
    }

    public void CancelEdit()
    {
        if(!_isInEditMode)
            throw new InvalidOperationException("CancelEdit without a BeginEdit"); 
        _isInEditMode = false;
        ClearItems();
        _bakupList.ForEach(Add);
        _bakupList = null;
    }

    #endregion
}

Some unit test to see what you can do:

[Test]
public void can_add_and_cancel()
{
    var editableList = new EditableCollection<string>
                           {
                               "a","b","c"
                           };
    
    editableList.BeginEdit();
    editableList.Add("f");
    editableList.CancelEdit();

    editableList.Should().Have.SameSequenceAs("a,b,c".Split(','));
    

}

[Test]
public void can_remove_and_cancel()
{
    var editableList = new EditableCollection<string>
                           {
                               "a","b","c"
                           };

    editableList.BeginEdit();
    editableList.Remove("c");
    editableList.CancelEdit();

    editableList.Should().Have.SameSequenceAs("a,b,c".Split(','));

}

[Test]
public void can_clear_and_cancel()
{
    var editableList = new EditableCollection<string>
                           {
                               "a","b","c"
                           };

    editableList.BeginEdit();
    editableList.Clear();
    editableList.CancelEdit();

    editableList.Should().Have.SameSequenceAs("a,b,c".Split(','));

}

This code is in uNhAddins.Wpf with the complete set of unit test. 


blog comments powered by Disqus
  • Categories

  • Archives