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.

Posted in .NET, C# Snippets, Windows Phone | Leave a comment

Protected: Snippet Example #1

This post is password protected. To view it please enter your password below:


Posted in Uncategorized | Enter your password to view comments.

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>
Posted in .NET, C# Snippets, Mango, Windows Phone, WP7 | Leave a comment

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.

Posted in .NET, C# Snippets, Mango, Windows Phone, WP7 | Leave a comment

Using LINQ to randomise a list.

This afternoon I needed to select some random items from a collection, and my searching ran into this idea.

Random rnd = new Random();
var randomizedList = from item in list
                     orderby rnd.Next()
                     select item;

I modified it a little to do what I needed (Select 4 items at random from a list), and this is what I came up with…

Random rnd = new Random();
var MyCollection = (from icon in TheOriginalList orderby rnd.Next() select icon).Take(4));
Posted in C# Snippets, Linq | Leave a comment

Bandwidth Throttling – WP7

I have been chasing down a defect in a Windows Phone 7 app that I’m involved with, but it seems to be bandwidth related. I really need to find a way to limit the bandwidth that the phone emulator is able to use.

On suggestion from some respected colleagues I used Fiddler to try to limit the bandwidth. There are a few extra steps you need to take to enable the emulator’s use of Fiddler, but once it is up and running you can use the “Simulate Modem Speed” option under Rules » Performance to limit the rate of data transmission. Sadly, though, in my instance the way fiddler handles this is not eally sufficient for me.

The config file for the rule lists the following section :

var m_SimulateModem: boolean = false;

if (m_SimulateModem){
  // Delay sends by 300ms per KB uploaded.
  oSession["request-trickle-delay"] = "300";
  // Delay receives by 150ms per KB downloaded.
  oSession["response-trickle-delay"] = "150";
}

Looking at the comments, it implies that it will add a delay of 150ms to each KB of data returned. Sadly, the amount of data I’m working with is so small that the bandwidth limiting isn’t able to make any difference.

So, now I’m looking for alternate ways to achieve my goal, preferably to limit the data coming back on a byte-by-byte basis rather than per KB chunk. If you have any ideas, please either leave a comment here or get in touch through Twitter (@ZombieSheep)

Thanks a lot. :)

Posted in Uncategorized | 2 Comments

iPad 2 : First impressions…

(Do they still qualify as “first impressions” after owning the device for more than 24 hours?)

Yesterday I managed to get my hands on an iPad 2. Bear in mind that I had always thought of the original iPad as a good idea, but a bit of a waste of time and money – I mean, 400 quid for an overgrown iPhone that doesn’t let you call anyone? That, though, was before I saw the GarageBand demo. I saw one video on YouTube and it changed the game for me. As some of you know, I am often called on the be away from home, so having a very capable 8 track studio in my laptop bag is a big draw.

Anyway, I patiently waited my opportunity to pick up one of the new generation, albeit the bottom of the range 16GB wifi model. They first thing that struck me was how well it sits in my hands. That Mr. Ive is a talented designer, and his stuff always looks the part but I hadn’t realised how natural these devices feel in use.

The bundled apps on the device are pretty good too. Safari has always been a great browser and the iOS version is no exception. The mail client took seconds to configure with my main email account, and the app store experience is a joy after using the Windows Phone 7 marketplace for a few months.

So now came the big moment – installing GarageBand. I was expecting it to be more difficult than it actually was, for some reason. In the end, I just found the app in the app store, clicked on the buy button, and a couple of minutes later I was up and running with my new (almost) pocket sized studio. Having used the full version on my MacBook I was familiar with most if the functions, and it took me literally 10 minutes to get a half way decent recording down using just e out of the box instruments. Adding in the iRig guitar adapter that I bought, I was recording guitar parts that sounded like they had been recorded for a lot more money than I had just shelled out (apart from the dodgy playing, obviously).

So, all in all I’m extremely happy with the iPad 2. If you are a friend on Facebook you may well have noticed a few posts to that effect. ;)

Now, if you’ll excuse me, I have to go explore the app store some more to find a good Facebook client…

20110409-032846.jpg

Posted in tools | Tagged , , , | Leave a comment

Barenaked Ladies – Leeds (17/10/10)

OK, first thing’s first – I am not what you’d call a Barenaked Ladies fan. I have a copy of “Stunt“, and I know “One Week” (in fact, my band have been trying to work out how to adequately cover it for a while now), but that’s not the point…. I went to see them on Friday night in Leeds and was pretty much blown away by them.

Obligatory photo from a camera phone

Barenaked Ladies - Leeds 17/10/2010

I can hear you asking yourself now “If you’re not a fan, why did you go see them?” Well, that’s a fair question, and the answer is simple. One of my mates *is* a big fan, and won the chance to go meet the band at the pre-show meet-and-greet. Once again, though, the answer gets a little more complicated – I didn’t go along with her, because she’d already promised the second ticket to another of out mutual friends. I did, however, offer to drive to take them and pick them up after the show (hey, I’m a nice guy!). Anyway, the suggestion was made that I may as well get a ticket and join them, so I did. (Although quite why I dedicated a whole paragraph to that little story is beyond me)

Anyway – the gig. I could ramble on for a while about the support acts, who were great, but I’m not going to. I’m just going to focus on the main event.

As I’ve already said, I was aware of the band, and some of their work, but in all honesty a lot of the material was new to me. Did that matter? Not a bit! The songs I did recognise were performed exactly as I’d have wished to see them, and the ones I didn’t know were catchy enough for it not to matter that this was the first time I’d heard them. The standard of musicianship was excellent, as you’d expect from the headline act. What I really wasn’t expecting, though, was the level of engagement with the audience, and the level of humour with which the whole show was presented. Not “we’re trying to be funny” kind of humour, just a gentle background feeling that I was watching a bunch of guys who were having a whale of a time on stage. I was standing fairly near the back (right alongside the sound engineer, actually – the sound is always great there) but I felt drawn in to the show, felt a part of the good feeling in the room, and felt as if I was the one they were here to entertain. No mean feat, as anyone who’s been up on a stage will tell you.

So, what’s the point of this rambling and unfocussed post? Well, just to tell you that if you get a chance to go see these guys perform you should take it and get out and have a great night’s entertainment. Next time they’re around these parts, I’ll be going again. Maybe I’ll see you there too.

**EDIT** Seems my tweet about this post was re-tweeted by Tyler. Another example of the band’s accessibility, I guess. :)

Posted in Uncategorized | 7 Comments

Split a Camel-Cased word into its components

I needed to split a camel-cased word into it’s component parts, and found the following extension method to help out. It works pretty well.

public static string SplitCamelCase( this string str )
{
return Regex.Replace( Regex.Replace( str, @"(\P{Ll})(\P{Ll}\p{Ll})", "$1 $2" ), @"(\p{Ll})(\P{Ll})", "$1 $2" );
}

20110409-060908.jpg

Posted in .NET, C# Snippets, Extension Methods, Uncategorized | Leave a comment

New Band

After a good few years playing with Hydra, I have started a new band. Four are similar to Hydra in the material we play, but we’re a four-piece (guitar, bass, drums and vocals) which makes my job as guitarist a bit more tricky.

Anyway, we have a very small, low-key gig planned for late April – mainly so we can try out some of our more eclectic material on a real audience. Hopefully it will go down as well with them as it has done with the band members so far. Let’s see, shall we?

4 in rehearsals

Posted in band, Guitars, Music | Leave a comment