I have
Observablecollection<A> aRef = new Observablecollection<A>(); bRef = aRef();
In this case both point to same ObservableCollection
. How do I make a different copy?
An ObservableCollection is a dynamic collection of objects of a given type. Objects can be added, removed or be updated with an automatic notification of actions. When an object is added to or removed from an observable collection, the UI is automatically updated.
The true difference is rather straightforward:ObservableCollection implements INotifyCollectionChanged which provides notification when the collection is changed (you guessed ^^) It allows the binding engine to update the UI when the ObservableCollection is updated. However, BindingList implements IBindingList.
ObservableCollection is a collection that allows code outside the collection be aware of when changes to the collection (add, move, remove) occur. It is used heavily in WPF and Silverlight but its use is not limited to there.
An IEnumerable is typically something you can enumerate - such as collections of items or generators. An ObservableCollection is a list that raises events when it's being modified. One is abstract and broad, the other concrete and specific. Note that ObservableCollection implements IEnumerable , among other interfaces.
Do this:
// aRef being an Observablecollection Observablecollection<Entity> bRef = new Observablecollection<Entity>(aRef);
This will create an observable collection but the items are still pointing to the original items. If you need the items to point a clone rather than the original items, you need to implement and then call a cloning method.
UPDATE
If you try to add to a list and then the observable collection have the original list, just create the Observablecollection by passing the original list:
List<Entity> originalEnityList = GetThatOriginalEnityListFromSomewhere(); Observablecollection<Entity> bRef = new Observablecollection<Entity>(originalEnityList);
You could implement ICloneable
interface in you entity definition and then make a copy of the ObservableCollection
with a internal cast. As a result you will have a cloned List
without any reference to old items. Then you could create your new ObservableCollection
whit the cloned List
public class YourEntity : ICloneable { public AnyType Property { get; set; } .... public object Clone() { return MemberwiseClone(); } }
The implementation would be
var clonedList = originalObservableCollection.Select(objEntity => (YourEntity) objEntity.Clone()).ToList(); ObservableCollection<YourEntity> clonedCollection = new ObservableCollection<YourEntity>(clonedList);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With