Using Several CollectionViewSources with the Pivot Control
September 25, 2010
One of the new (and shiny) controls in Windows Phone 7 is the Pivot. You can have up to 7 PivotItems i.e. lists that user can navigate with a swipe gesture. Here’s a quick video demonstrating a Pivot in action :
Vodpod videos no longer available.
The other example is the built-in email application from Microsoft where the Pivot is used to see Unread, Urgent, and Flagged messages. This is a perfect fit for the CollectionViewSource object which is very handy to expose a collection through a View. This view can be sorted, grouped and filtered without altering the source (your collection). So going back to the Wines page in the video, there’s just one source : an ObservableCollection<Wine> and 3 CollectionViewSources , each one with a filter.
The source code (the filter is only a Predicate method):
private ObservableCollection<Wine> wines; //ctor(..) protected override void OnNavigatedTo(NavigationEventArgs e) { FavoriteWines = new CollectionViewSource{ Source = wines }; FavoriteWines.View.MoveCurrentTo(-1); WishWines = new CollectionViewSource{ Source = wines }; WishWines.View.MoveCurrentTo(-1); LocateWines = new CollectionViewSource{ Source = wines }; LocateWines.View.MoveCurrentTo(-1); FavoriteWines.View.Filter = (x) => FilterWine(x, ListType.MyWines); WishWines.View.Filter = (x) => FilterWine(x, ListType.WishList); LocateWines.View.Filter = (x) => FilterWine(x, ListType.Locate); }
In the XAML :
<Controls:Pivot Style="{StaticResource PivotStyle}"> <Controls:PivotItem Header="My Wines"> <ListBox x:Name="MyWinesListBox" ItemsSource="{Binding FavoriteWines.View}"> <ListBox.ItemTemplate> <DataTemplate> <userControls:WineSummary DataContext="{Binding}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Controls:PivotItem> <Controls:PivotItem Header="WishList"> <ListBox x:Name="MyWishListBox" ItemsSource="{Binding WishWines.View}"> <ListBox.ItemTemplate> <DataTemplate> <userControls:WineSummary DataContext="{Binding}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Controls:PivotItem> <Controls:PivotItem Header="Locate"> <ListBox x:Name="MyLocateWines" ItemsSource="{Binding LocateWines.View}"> <ListBox.ItemTemplate> <DataTemplate> <userControls:WineSummary DataContext="{Binding}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Controls:PivotItem> </Controls:Pivot>
And that’s it for an old concept of WPF/Silverlight that can be easily applied in Windows Phone 7 to manage the Pivot control.
No comments yet