Is there any differences between following code snippets?
I'm using VS 2010, .NET 4, WPF
Code Snippet 1:
List<EPutAway> listEPutAway = new List<EPutAway>(); // 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 }
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.
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