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, WPFCode 开发者_JS百科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.
精彩评论