Atif Shabeer
Atif Shabeer

Reputation: 555

List To ObservableCollection

I am writing a Windows Phone 8.1 App. It is getting JSON from server and deserializing it and storing it into List. I have ListView bound to this List. Now if the new items are added to List, ListView isn't updated. So, I am trying to convert change this List into ObservableCollection. But I am confused about samples and tutorials on internet.

XAML:

 <DataTemplate 
            x:Key="StandardProductsItemTemplate">
            <Grid >
                <StackPanel 
                    Orientation="Vertical">
                      <Image 
                    Source="{Binding ProductImage}" 
                        x:Name="ImageDisplay"/>                        
                     <TextBlock 
                    Text="{Binding ProductName}"/>
                </StackPanel>
            </Grid>
        </DataTemplate>

C#:

List<Product> ProductsObject = new List<Product>();

 for (int i = 0; i < GetProductByCategoryResultObject.Products.Count; i++)
            {
             ProductsObject.Add(GetProductByCategoryResultObject.Products[i]); 
            }
ProductListView.ItemsSource = ProductsObject;

Now, I want to use ObservableCollection instead of list for ListView to remain Updated. Please help

Upvotes: 0

Views: 506

Answers (2)

Vyas
Vyas

Reputation: 2784

ObservableCollection<Product> ProductsObject = new ObservableCollection<Product>();

 for (int i = 0; i < GetProductByCategoryResultObject.Products.Count; i++)
            {
             ProductsObject.Add(GetProductByCategoryResultObject.Products[i]); 
            }
ProductListView.ItemsSource = ProductsObject;

Upvotes: 2

Lennart
Lennart

Reputation: 10354

You can simply replace your list by an ObservableCollection, the syntax in your example stays the same:

ObservableCollection<Product> ProductsObject = new ObservableCollection<Product>();

 for (int i = 0; i < GetProductByCategoryResultObject.Products.Count; i++)
     {
      ProductsObject.Add(GetProductByCategoryResultObject.Products[i]); 
     }
ProductListView.ItemsSource = ProductsObject;

Upvotes: 2

Related Questions