Home > Windows Phone > Accent Windows Phone List Items With Binding Convertors

Accent Windows Phone List Items With Binding Convertors

Imagine scenario in your Windows Phone application where you have to display some items in ListBox (or LongListSelector) control in phone accent color based on some property in bounded collection. This can be easily implemented with Binding Convertors which purpose is to convert data on its way from the source to the target and (if necessary) back the other way. Binding converters are simple classes of type IValueConverter, an interface that requires only two methods named Convert and ConvertBack. Convert handles the data conversion from the source to the target, and ConvertBack handles the conversion going in the other direction for a TwoWay binding. If you ever worked with popular Coding4fun toolkit, you probably noticed (and used, I hope) BooleanToVisibilityConverter, StringToVisibilityConverter, ThemedImageConverter, etc. More about Binding Converters and their use with Coding4fun toolkit you can found on following address.

Let’s go back to our example. If we want converter that will change style of UI element to Accent color of your phone, based on some Boolean value, first we have to create new converter class:

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace AccentListItems.Wp8
{
    public class AccentConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is bool)
            {
                bool isAccent = (bool)value;
                if (isAccent)
                    return App.Current.Resources["PhoneTextAccentStyle"] as Style;
                else
                    return App.Current.Resources["PhoneTextNormalStyle"] as Style;
            }
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    }
}

Covert method is very simple; if source value if true return PhoneTextAccentStyle style, otherwise return PhoneTextNormalStyle style. Note that you can extend this method to work with any other type of source data.

Now we can use this converter in in our XAML page. First add the converter’s prefix namespace to page (put it in phone:PhoneApplicationPage section):

xmlns:local="clr-namespace:AccentListItems.Wp8"

Next step is to define converter’s instance in page. Put following code in page resources section:

<phone:PhoneApplicationPage.Resources>
    <local:AccentConverter x:Key="AccentConverter"/>
</phone:PhoneApplicationPage.Resources>

 

Now we have to add ListBox. This example is for WP8, so we will add LongListSelector. I also recommend you to use Coding4fun LongListSelector in WP7 version, but you can use ListBox control also (at the end of this post you will find download links for complete solutions; WP7 version uses ListBox).

<phone:LongListSelector
    Name="listBoxCities" 
    ItemTemplate="{StaticResource CityItemTemplate}">
</phone:LongListSelector>

 

In resource section of page add list items template:

<phone:PhoneApplicationPage.Resources>
    <local:AccentConverter x:Key="AccentConverter"/>

    <DataTemplate x:Key="CityItemTemplate">
        <StackPanel Orientation="Vertical" >
            <TextBlock 
                FontSize="26"
                Style="{Binding Path=IsAccent, Converter={StaticResource AccentConverter} }"
                Text="{Binding Name}" />
            <TextBlock 
                Margin="12,0,0,12"
                Style="{Binding Path=IsAccent, Converter={StaticResource AccentConverter} }"
                FontSize="18" 
                Text="{Binding Country}" />
        </StackPanel>
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>

 

In our example we will bind list to collection of cities, which is defined in following class:

using System;
using System.ComponentModel;

namespace AccentListItems.Wp8
{
    public class City
    {
        public string Name { get; set; }
        public string Country { get; set; }
        public string IsAccent { get; set; }
    }
}

 

Color of binded cities in list box will change to Accent color if value of IsAccent property of city is true.

Let’s see complete code behind this page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;

namespace AccentListItems.Wp8
{
    public partial class MainPage : PhoneApplicationPage
    {
        private ObservableCollection<City> cities;

        public MainPage()
        {
            InitializeComponent();
            this.InitCities();
        }

        private void InitCities()
        {
            cities = new ObservableCollection<City>();
            cities.Add(new City() { Name = "Sacramento", Country = "USA", IsAccent = false });
            cities.Add(new City() { Name = "Toulouse", Country = "France", IsAccent = true });
            cities.Add(new City() { Name = "Augsburg", Country = "Germany", IsAccent = true });
            cities.Add(new City() { Name = "Nagano", Country = "Japan", IsAccent = false });
            cities.Add(new City() { Name = "Zadar", Country = "Croatia", IsAccent = true });
            listBoxCities.ItemsSource = cities;
        }

    }
}

 

Start your app and here is result (cities from Europe are accented):

screenshot1

Complete working zip solution for Windows Phone 7 and 8 can be downloaded from here.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: