Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between using ItemsSource and foreach loop to assign data in a ListView?

Is there any differences between following code snippets?
I'm using VS 2010, .NET 4, WPF

Code Snippet 1:

  List<EPutAway> listEPutAway = new List&ltEPutAway>();
  // assign some data in listEPutAway here
  lvPutWaySearch.ItemsSource = listEPutAway;   // lvPutWaySearch is a ListView

Code Snippet 2:

  List<EPutAway> listEPutAway = new List<EPutAway>();
  // assign some data in listEPutAway here
  foreach (var ePutAway in listEPutAway)
                {
                    lvPutWaySearch.Items.Add(ePutAway); // lvPutWaySearch is a ListView
                }
like image 270
Towhid Avatar asked Jan 20 '23 01:01

Towhid


1 Answers

There is a very big difference.

In the first scenario, you are binding to the listEPutAway collection. This means that if the collection implements INotifyCollectionChanged, any changes to it will automatically be reflected in the control that binds to it.

Of course, in this specific example, List (which class exactly is that?) probably does not implement this interface. Usually when binding you elect to bind to an ObservableCollection<T> for this specific reason.

In the second scenario, you provide the list of items to the control manually. The data in the control is then completely independent from anything else that might be going on in your application.

One of the major attractions of WPF is specifically support for data binding, so "the WPF way" is the first scenario (and declaring the binding in XAML as well).

As a sidenote, you should have in mind that it isn't possible to use Items (manual population) and ItemsSource (data binding) at the same time.

like image 183
Jon Avatar answered Feb 23 '23 00:02

Jon