Make a HubSection in Windows Phone Store apps bigger then one screen
In Windows Phone Silverlight apps we could make a PanoramaItem wider then one screen, so you had to scroll a little to see the whole section. In this blog post I show you how you can do the same with the Hub control. The hub control replaces the Panorama control in Windows Phone Store apps.
Which things are changing?
- We have a new control, hub instead of panorama which means having new API we have to figure out.
- We no longer know the scrreenwidth. In Windows Phone 8 the screenwidth was always the same. With Windows Phone 8.1 it isnt. For Windows Store apps developers this isnt new but for phone we have to make our applications with a more responsive design.
And will want to follow the guideliness, so a hubsection page need to be a whole screen, not just 40% of a screen.
So given that, we cant set the width of a HubSection directly to a fixed value. If we do this it wont look nice on all kind of resolutions.
We can't use auto. If we start using auto it can happen a page takes just a small part of the next page.
So in code we have to calcute the page. Which isnt very hard. A hub section should take 90% of the screenwidth and use the remaining 10% to hint about the next page.
That gives the next formula:
width = numberOfPages * (totalScreenwidth * 0.9)
and in code:
hubSection.Width = numberOfScreens * (Window.Current.CoreWindow.Bounds.Width * .9);
You can simple put this in code behind or make it reusable. Now there are a lot of different approaches:
- Converter
- Behavior
- Attached Property
I personally like the attached property way; The class can look like this:
public class HubSectionExtensions : DependencyObject { public static int GetNumberOfScreens(DependencyObject obj) { return (int)obj.GetValue(NumberOfScreensProperty); } public static void SetNumberOfScreens(DependencyObject obj, int value) { obj.SetValue(NumberOfScreensProperty, value); } public static readonly DependencyProperty NumberOfScreensProperty = DependencyProperty.RegisterAttached("NumberOfScreens", typeof(int), typeof(HubSectionExtensions), new PropertyMetadata(1, OnNumberOfScreens)); private static void OnNumberOfScreens(DependencyObject d, DependencyPropertyChangedEventArgs e) { HubSection hubSection = d as HubSection; if (hubSection != null) { const double percentageWidth = .9d; int numberOfScreens = (int)e.NewValue; hubSection.Width = numberOfScreens * (Window.Current.CoreWindow.Bounds.Width * percentageWidth); } } }
in xaml you can easily use this:
<HubSection x:Uid="HubSection2" Header="SECTION 2" local:HubSectionExtensions.NumberOfScreens="2" DataContext="{Binding Groups[0]}" HeaderTemplate="{ThemeResource HubSectionHeaderTemplate}">
and thee result will look like this