Category Archives: Windows Phone

WP7 Navigation Gotcha

This afternoon I discovered a bug in one of the apps I am working on. It happens because the keys we use for navigation are provided in a third-party feed, and one of those keys contains a plus sign (“+”).

This wasn’t immediately apparent as an issue, and we just navigated using

NavigationService.Navigate(new Uri("/Views/TargetView.xaml?key=" + myKeyValue, UriKind.Relative));

Unfortunately, this gets UrlDecoded on the receiving side as a sapce, so our key that started out being “text+text” was being resolved as “text text”. When looking that value up in our tables the key was obviosuly not found and a NullReferenceException was thrown.

The fix was pretty simple, though. We just had to UrlEncode the strong before we sent it, as follows.

NavigationService.Navigate(new Uri("/Views/TargetView.xaml?key=" + System.Net.HttpUtility.UrlEncode(myKeyValue), UriKind.Relative));

and all is good with the world again.

Silverlight Toolkit ExpanderView – Flat Objects

Before anyone posts, I know this is not the intended usage of the control. I did, however, have a requirement to show a list of simple objects and some of their properties in an expander view, so I’m going to explain one of many possible ways to do it.

My ViewModel contains an ObservableCollection<ServiceAddOn>, where my ServiceAddOn class looks like this.

public class ServiceAddOn : INotifyPropertyChanged
{
    string name;
    string cost;
    DateTime startDate;
    DateTime expiryDate;
    // encapsulation for public access to the 4 locals
    // INotifyPropertyChanged implementation
}

Don’t worry about the encapsulation or INotifyPropertyChanged implementation – they are as simple as it gets.

Now, I want to create an ListBox of ExpanderView controls that will display the information like this :


My Item Name
- Cost : £123.99
- Start Date : 1/1/2012
- Expiry Date : 1/1/2013
Second Item
ThirdItem

That is where the problems start. As far as I can tell (with admittedly limited research into the issue) there is no way to bind to properties of an object in both the HeaderTemplate and the ItemTemplate – something needed to be done to expose these properties as a collection. Since I was not able to change the inplementation of the ServiceAddOn class, I decided the best way would be to write a converter. Before starting that, though, I needed a class to hold each of myt exposed properties. It looks like this :

public class ExposedProperty
{
    public string Key { get; set; }
    public string Value { get; set; }
}

Again, it is about as simple as it gets. :)

Now, the converter:

public class ExposePropertyConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        ServiceAddOn obj = value as ServiceAddOn;
        if (null == obj) return null;
        ObservableCollection<ExposedProperty> values = new ObservableCollection<ExposedProperty>();
        values.Add(new ExposedProperty { Key = "Cost", Value = obj.Cost });
        values.Add(new ExposedProperty { Key = "Start Date", Value = obj.StartDate.Date.ToShortDateString() });
        values.Add(new ExposedProperty { Key = "Expiry Date", Value = obj.ExpiryDate.Date.ToShortDateString() });

        return values;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

So now, it is just a case of a bit of plumbing…

Add the namespace reference to the XAML, and declare a converter instance

<phone:PhoneApplicationPage 
    x:Class="MyExampleApp.MainPage"
    ...snip...
    xmlns:conv="clr-namespace:MyExampleApp.Converters"
    ...snip...
    >
    <phone:PhoneApplicationPage.Resources>
        <conv:ExposePropertyConverter x:Key="GetMyProperties" />
    </phone:PhoneApplicationPage.Resources>

and then wire up the Listbox / ExpanderView combo… (note tht my collection of ServiceAddOn objects is called “DisplayItems”)

<ListBox ItemsSource="{Binding DisplayItems}">
    ...snip standard plumbing...
    <ListBox.ItemTemplate>
        <DataTemplate>
             <toolkit:ExpanderView 
                 ItemsSource="{Binding Converter={StaticResource GetMyProperties}}"
                 Header="{Binding}"
                 NonExpandableHeader="{Binding}"
                 Expander="{Binding}">
                 <toolkit:ExpanderView.HeaderTemplate>
                     <DataTemplate>
                         <TextBlock Text="{Binding Name}" />
                     </DataTemplate>
                 </toolkit:ExpanderView.HeaderTemplate>
                 <toolkit:ExpanderView.ItemTemplate>
                     <DataTemplate>
                         <TextBlock>
                             <Run Text="{Binding Key}" />
                             <Run Text=" : " />
                             <Run Text="{Binding Value}" />
                         </TextBlock>
                     </DataTemplate>
                 </toolkit:ExpanderView.ItemTemplate>
             </toolkit:ExpanderView>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

The “magic” happens on line 6, where I bind the ItemsSource of the ExpanderView control to “{Binding Converter={StaticResource GetMyProperties}}”.

That’s it.

Next steps for this may be to make the Converter more generic, and possibly use reflection to get the properties instead of hard coding them, but for now this is good enough.

If you have any comments about a much simpler way to bind to flat, single-level objects in an ExpanderView control. I’d love to hear them.

Alter a Pivot controls header template the easy way (WP7)

If you want to alter the template for a Windows Phone 7 pivot control’s header, the simplest way is as follows…

        <controls:Pivot Title="Altered Styles">
            <controls:Pivot.HeaderTemplate>  
                <!-- This changes to look of the items headers -->
                <DataTemplate>
                    <TextBlock Text="{Binding}" Foreground="Black"/>
                </DataTemplate>
            </controls:Pivot.HeaderTemplate>
            <controls:Pivot.TitleTemplate>
                <!-- This changes to look of the pivot overall title -->
                <DataTemplate>
                    <TextBlock Text="{Binding}" Foreground="Black"/>
                </DataTemplate>
            </controls:Pivot.TitleTemplate>
            <controls:PivotItem Header="daily">
                <Grid/>
            </controls:PivotItem>
            <controls:PivotItem Header="hourly">
                <Grid/>
            </controls:PivotItem>
        </controls:Pivot>

Of course, all this example does is specifically set the colour used for the title and headers to black, but you can do (almost) whatever you like in those templates. Want to add an image as a bullet? Go for it.

<controls:Pivot.HeaderTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <Image Height="48" Width="48" Source="/MyBulletImage.png" />
            <TextBlock Text="{Binding}" Foreground="Black"/>
        </StackPanel>
    </DataTemplate>
</controls:Pivot.HeaderTemplate>

Alternating ListBox item background colours in WP7

I had a requirement today to implement alternating row colours in a Windows Phone 7 ListBox. After a bit of frustration with searching and only finding answers tht said “You can’t do it”, or that you need to add a property on the model to bind the background to, I eventually hit upon a nugget of common sense on this page.

Basically you need to create a converter class that will handle the alternation of backgrounds for you. It is ridiculously simple once you see it in action.

Step 1 : Create the converter.

public class AlternateRowColour : IValueConverter
{
bool isAlternate;
SolidColorBrush even = new SolidColorBrush(Colors.Transparent); // Set these two brushes to your alternating background colours.
SolidColorBrush odd = new SolidColorBrush(Color.FromArgb(255, 241, 241, 241));

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
isAlternate = !isAlternate;
return isAlternate ? even : odd ;
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

Step 2 : Add the converter to the page

<UserControl
 	...snip...
 	xmlns:conv="clr-namespace:MyApplication.Converters" 
 	...snip...
 	>
	<UserControl.Resources>
		<conv:AlternateRowColour x:Key="RowColour" />
	</UserControl.Resources>
	...snip...
</UserControl>

Step 3 : Bind to the ListBox

<ListBox ItemsSource="{Binding}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <Grid Background="{Binding Converter={StaticResource RowColour}}">
        <!-- layout XAML -->
      </Grid>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>				

And you’re done.