Search code examples
xamllistviewwindows-phone-8.1pivotreusability

Using the same ListView on two PivotItems without code duplication


I'm working on a shopping Windows Phone 8.1 application, where I have a "Promotions" page. This page is a Pivot page with two PivotItems. The first Item shows the top 100 promotions, and the second Item shows all the promotions. To get the data I call a webservice. The data has the same structure in both cases, so I use the same ListView and DataTemplate on both pages. My question is: how can I avoid code duplication in this scenario? How can I use the same ListView and DataTemplate on the two PivotItems without copy-pasting XAML and code?


Solution

  • You need to create another property in your viewmodel that takes a filter of the first like this:

        public ObservableCollection<ItemModel> ItemList { get; set; }
        public IEnumerable<ItemModel> Top100List { get { return (from i in ItemList select i).Take(100); } }
    

    Then bind each ListView to the appropriate property. This example assumes that the top 100 items are the first 100 items in the list. If they are not, then you will either have to modfy the linq statement or sort the list when adding items.