I have seen this post
Pros and Cons of using Observable Collection over IEnumerable
My Questions are for ComboBoxes/ListBoxes :
Is there a summary of what type of collections could be used in this kind of binding, I mean which collection type can be used for binding to an ItemsSource for ListBoxes/ComboBoxes Kind. Which interfaces does each of these collection has to implement in order to be able to be bound to an ItemsSource
Does any of these Collection offer certain disadvantage/advantages over the other in terms of rendering speed and async advantages, lets say with virtualization set to on? Or it does not matter once the ItemsSource has been set?
Enumerable
ReadOnlyCollection
ObservableCollection
...
I can't answer the speed comparison you ask for since the things listed are completely different things.
Let me explain that briefly:
IEnumerable is just an interface that provides you with a bunch of extension methods and iterator functionality. Notable collection classes that implement IEnumerable would be e.g. a Dictionary<>, or an ObservableCollection<> or a List<> for that matter.
ReadOnlyCollection (and I assume you don't mean IReadOnlyCollection) is a concrete implementation of IReadOnlyCollection that wraps around an existing class that implements the IList interface. You pass that into the constructor and it will give you read only access to the content of the collection.
ObservableCollection implements among other things IEnumerable and IList interfaces.
Assuming from the context of your question you ask if there are specific collections that you can bind to ComboBoxes or ListBoxes and alike that are preferable in terms of speed.
Let's look at the WPF ComboBox:
Its ItemsSource property asks for an IEnumerable, and as stated above you can use any concrete class that implements that interface. You mentioned ObservableCollection, that one is interesting because it implements the INotifyCollectionChanged interface.
It allows you to do the following: Once you have an ObservableCollection bound to the ItemsSource of the ComboBox if you e.g. Add() or Remove() items from it the ComboBox will get notified of the change and reflect that by adding, or removing items from the list of visible things in the dropdown. If you used e.g. a List<> instead that would not happen and you would have to rebind/reassign the ItemsSource again.
Let's get back to the speed question, we can break that down into several parts:
Construction of your collection:
A List will be cheaper to construct than an ObservableCollection
simply because of the fact that Observable collection has to
repeatedly raise the CollectionChanged event. So if you know that
you collection never changes and you can construct it completely
before you assign it to the ItemsSource you can use a List
instead.
Maintainance of the collection: As mentioned in 1. if the collection never changes and can be pre-constructed, don't use an ObservableCollection, use the List
instead
(Probably most interesting for you) Rendering of items: Depending on the Container (e.g. ListBox or ComboBox or any other for that matter) the largest amount of time will be spent
rendering the items unless the control virtualizes the items.
--What does #3 that mean?
Imagine you have a collection of 300 items and assign that to your container:
If it is not virtualized it will start rendering all 300 items which takes a while but you will likely only see a subset of them on the screen all the other ones are hidden and you have to move a scrollbar to get them into view.
If the control can virtualize it will render only the part you can see right now and maybe a couple extra directly adjacent and then when you scroll start rendering the ones that come into view on demand. This is significantly faster initially and maybe a little bit slower during scrolling.
Points 1 and 2 are likely very negligible for such small lists with 300 items, however you will likely want to look into #3. Even already for smaller datasets virtualization makes a huge difference because most of the time is spent rendering especially if you have complex/slow Styles or DataTemplates
This might not directly answer your question but will instead give you a hint into which direction to focus your efforts.
Related
From what I can gather from Intellisense, the difference is the return types and the ItemsSource has a setter whereas Items simply has a getter. Practically speaking though, I do not understand the need for these two properties being separate from each other instead of just being one property.
Could someone explain to me why these are separate properties instead of just one property?
And also, if I'm missing something, could someone please explain to me when I'd want to use one over the other (besides the obvious need of a setter)? E.g., when specifically would I want to use Items over ItemsSource?
What's the difference between a WPF DataGrid's Items and ItemsSource properties?
A DataGrid is an ItemsControl so this applies to all other ItemsControl classes as well.
The Items property is an ItemCollection and is filled in through XAML. It holds objects but is intended for FrameworkElements.
The ItemsSource is bindable to a simple IEnumerable, with the ability to support INotifyCollectionChanged when available. It also supports DataTemplates.
when specifically would I want to use Items over ItemsSource?
ItemsSource is for databinding to a ViewModel.
You would use Items only in a few situations where you have a fixed number of XAML items. Unlikely for a Grid, more usable for a ComboBox.
You never use both at the same time.
This MSDN Page shows the typical usage for both.
I have to make some programs in c# and in order to perform IO between programs i have to use, or property using INotifyPropertyChange(on a List<>) or ObservableCollection<>.
I'd like to know which one is the better to perform IO operation between c# programs.
Thank you for reading
Based on the criteria you list in the question & comments, you're best off with an ObservableCollection.
The INotifyPropertyChanged interface exists to tell you just that - a property changed. When you're talking about a list, the properties will be things like Count and Item[]. This means that, effectively, all you're actually being told is "the contents of the list have changed" but not any details as to what that change actually was. Without any such information, all your control can really do is redraw itself completely based on the current state of the collection.
With ObservableCollection, however, you get told when an item is added (and what that item was and where it was added) and when an item is removed (and what that item was and where it used to be). This is enough information for your UI control to only have to redraw what has actually changed, which is far more efficient than redrawing the entire thing. This is why ObservableCollection was invented - use it!
Take a note that ObservableCollection inherits both INotifyCollectionChanged, and INotifyPropertyChanged.
[SerializableAttribute]
public class ObservableCollection<T> : Collection<T>,
INotifyCollectionChanged, INotifyPropertyChanged
See documentation from link above:
In many cases the data that you work with is a collection of objects. For example, a common scenario in data binding is to use an ItemsControl such as a ListBox, ListView, or TreeView to display a collection of records.
You can enumerate over any collection that implements the IEnumerable interface. However, to set up dynamic bindings so that insertions or deletions in the collection update the UI automatically, the collection must implement the INotifyCollectionChanged interface. This interface exposes the CollectionChanged event, an event that should be raised whenever the underlying collection changes.
WPF provides the ObservableCollection class, which is a built-in implementation of a data collection that implements the INotifyCollectionChanged interface.
Before implementing your own collection, consider using ObservableCollection or one of the existing collection classes, such as List, Collection, and BindingList, among many others. If you have an advanced scenario and want to implement your own collection, consider using IList, which provides a non-generic collection of objects that can be individually accessed by index. Implementing IList provides the best performance with the data binding engine.
INotifyPropertyChanged is used to notify the UI when the bounded property value or collection is changed. Whereas ObservableCollection is used to notify the UI when the bound collection is modified(Ex adding or removing object from the collection) It cant notify the UI if the property value in one of the collection object is changed.
These two alternatives do not do the same thing. You are choosing between these two options:
a list property implementing INotifyPropertyChanged, where you throw the event every time the list is modified
a property of type ObservableCollection
With option 1, when you modify the list, an event is raised that says "the entire list has changed." If you have a UI element bound to this list (say, a ListBox), the entire element will have to be redrawn, because it has to assume that the entire list has been changed (that is: it may no longer be the same list!).
With option 2, you are raising specific events about individual items that were added or removed in the list. If you have a UI element bound to this list, it can respond by only modifying the UI that is relevant for these elements.
Consider the example where you remove an item from your list, and the list is bound to a WPF ListBox control. With option 1, the entire content of the list is re-created. With option 2, the removed item's control is removed but the rest of the list is left intact.
It should be clear from this example that the ObservableCollection - because it supports an event that is specific to what you are doing - will be more efficient in many cases. That said, unless you have a huge amount of data in the collection or a very complex UI, the performance gain will be negligible. Further, if you're making large modifications to your list, you may well find that it's faster to refresh the whole list.
Ultimately, no performance question can be answered accurately on StackOverflow without repeating the mantra: profile your code, and make a decision based on the results.
I have a setup where potentially thousands of items (think 3000-5000) will be added to an ObservableCollection that is binded to some visual interface. Currently, the process of adding them is quite slow (approx. 4 seconds/1000 items), and of course the GUI is unresponsive during that time. What is a good method to handle moving that many items at once into a collection without worrying about the system locking up? I've looked at DispatcherTimer but I'm not sure if it will provide everything I need it to.
Another question - Is there something I can do to speed up the creation of these objects so that it doesn't take so long to add them to the collection? Currently I use them like so: Collection.Add(new Item(<params>)) Would generating the items beforehand, in a background thread probably, decrease the time it takes to add them by a noticeable amount?
Edit: Virtualization is not possible. The requirements specify a WrapPanel look, so the display is actually a ListBox which has a templated ItemsPanel
Edit2: According to the stopwatch, the bottleneck is actually putting items into my ObservableCollection. I will try changing that collection type and doing my own notification to see if that speeds it up substantially.
Edit3: So the answer is in one place - I solved this issue (with help from below) by creating a class which inherits from ObservableCollection. This class did two things - expose a method to add collections at one time, and added the ability to suppress the CollectionChanged Event. With these changes the time it takes to add 3000 items is roughly .4 seconds (97% improvement). This link details the implementation of these changes.
You've said 1000, so I'll stick to that number just for instance.
IIRC, the observable collection has a small drawback - if you add the items one by one, it raises notifies once per each item. That means that you have 1000 notifications for 1000 of items and the UI thread will run at deadly speed just to keep up with redrawing the screen.
Do you need to redraw ASAP? Maybe you can batch the additions? Split the 1000 of items into a few packed of 100 items, or a little more packets of 50 or 20 items. Then, instead of putting all items one by one, put them in packets. But beware: you have to use some methods like AddRange implemented by the collection it self, not by LINQ, or else you will again have one-by-one insertion. If you find such method, it should cut the number of events significantly, because the collection should raise the Changed event only once per AddRange call.
If observable collection does not have AddRange, either use different collection, or write your own, just a wrapper will probably be sufficient. The goal is to NOT raise Changed event at every single Add(), but after a reasonable count of them, or - maybe just skip raising Changed when items are added and raise Changed at some regular time intervals? This would be beneficial especially, if your data "flows in" indefinitely at a constant rate.
Of course, at that number of items coming onto the screen, you may just as well be held at the rendering it self. If your ItemTemplates are complicated, a 1000 of objects times 1000 of instances of visual layers/properties may simply kill the user experience. Have you simplified the ItemTemplates to the bare minimum?
Last thing: consider using virtualizing StackPanels as the ItemPanels in your ItemsControl/ListBoxes. It can greatly reduce the memory footprint and the number of items drawn at a single point of time. This will not necessarily help in the number or events raised, but it may help greatly when you have complex item templates!
Edit: you are using ObservableCollection, so I've assumed WPF/Silverlight.. update the question if this is not correct
WPF Binding supports concurrency for this reason. Try setting Binding.IsAsync to true. In addition.
Don't use ObservableCollection<T>, it is slow for this because each time an item is added it raises events. Use something faster like List<T> and raise your property change notification after all your items are added.
Pre-create your items in a background thread, then push them into your collection.
Check other parts of code involved to see if there is bloat, and trim.
By request, here is how I solved this issue. I started by creating a class which inherits from ObservableCollection. This class did two things - expose a method to add entire collections at once, and added the ability to suppress the CollectionChanged Event. With these changes the time it takes to add 3000 items is roughly .4 seconds (97% improvement). This link details the implementation of these changes.
Another thing you can try: subclass ObservableCollection and make it support bulk loading (AddRange). Here is an article:
AddRange and ObservableCollection
for second question
if in your GUI you are using WPF technologie, you can increase performance using VirualizingStackPanel allowing you to create only visible items
I'm look for some direction.
I need a Sortable collection of objects which can also notify when items are added / removed from this collection as I'm binding it to a menu items as a list of windows open in my application.
Could someone please advise which would be a good collection type i.e. List<>, ObservableCollection et cetera and how I would go about sorting the said collection.
Many Thanks in advance.
This is sortable observable collection
And here is another implementation - I use this one in my project, works flawlessly (I just had to extend it so it implements also IList interface, so it can be used to define collections in XAML).
You could try and wrap your ObservableCollection in a CollectionView, notifications will be propagated and you can sort, filter and group items.
Note that the sorting does not modify the source collection which might be a problem if you need the changes to be permanent, then again only yesterday i used the class for the first time so don't know much about it, maybe you can apply the sorting to the source somehow.
Have you tried using System.Windows.Forms.BindingSource along with a System.Windows.Forms.BindingNavigator? These will do exactly what it sounds like you need- bind a collection of objects to a navigable menu.
As for sorting, you just have to get a list of the BindingSource's items, clear the BindingSource, do your sorting on the list, and add the sorted items to the BindingSource again.
See these links for helpful examples:
http://msdn.microsoft.com/en-us/library/b9y7cz6d.aspx
http://www.code-magazine.com/article.aspx?quickid=0507051&page=2
http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.languages.csharp/2008-09/msg01820.html
http://blogs.msdn.com/b/dchandnani/archive/2005/03/09/391308.aspx
Thanks for all the responses.
Was able to simplify things as I realised I only needed the collection to be sorted for display purposes when binding to the menu items.
I was therefore able to use the following code to sort my list of panel objects via menu item parent (miPanels) in this case. (PanelName being one of the properties of the object)
miPanels.Items.SortDescriptions.Add(new SortDescription("PanelName", ListSortDirection.Ascending));
Once again thanks for all the people who took the time to look and respond.
I would like to know why according to this article and observable collection binds significantly faster(20 ms vs 1685ms, that's 800X faster) than a List<> collection in WPF. I looked at the internals of ObservableCollection and it uses a List as it's storage collection object(I used reflector and saw this in the constructor)
public Collection()
{
this.items = new List<T>();
}
So what's going on here?
The comparison in that article isn't between two simple binding operations, those measurements refer to a scenario in which you add a single item to a WPF ListBox that is already bound to either a List<T> or an ObservableCollection<T>.
As the author remarks:
...the CLR List<T> object
does not automatically raise a
collection changed event. In order to
get the ListBox to pick up the
changes, you would have to recreate
your list of employees and re-attach
it to the ItemsSource property of the
ListBox. While this solution works, it
introduces a huge performance impact.
Each time you reassign the ItemsSource
of ListBox to a new object, the
ListBox first throws away its previous
items and regenerates its entire list.
This explains the performance difference. Even though ObservableCollection<T> is backed by a List<T>, it implements the INotifyCollectionChanged interface, which renders all that extra processing unnecessary.