What is the difference between using ItemsSource and foreach elements to assign data to a ListView?

Are there any differences between the following code snippets?
I am 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

Fragment Code 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
                 }
+4
source share
1 answer

There is a very big difference .

In the first scenario, you bind to the listEPutAway collection . This means that if a collection implements INotifyCollectionChanged , any changes to it will automatically be displayed in the control that is bound to it.

Of course, in this concrete example, List (which class?) Probably does not implement this interface. Typically, when binding, you select the binding to the ObservableCollection<T> for this specific reason.

In the second scenario, you specify a list of controls manually. Then the data in the control is completely independent of everything that might be in your application.

One of the main attractions of WPF is its specific support for data binding, so the "WPF path" is the first scenario (and the binding declaration in XAML as well).

As a side element, you should keep in mind that it is impossible to use Items (manual collection) and ItemsSource (data binding) at the same time.

+8
source

Source: https://habr.com/ru/post/1347532/


All Articles