Silverlight Grid Row Gradients

I just had to implement a design where a table of data, in Silverlight, had to have cell backgrounds where each cell is slightly darker than the cell above. Here it is in situ:

As you can see, not only does each row have a descending gradient, but each column has a different gradient.

The easy way

The simple way is to just put in a border or background rectangle into each cell. This is what I did originally. But it’s a lot of work no matter how you do it. Neither Blend nor Visual Studio lend themselves to this kind of thing, and even hand-editing the Xaml can lead to cut&paste errors.

The even easier way

I decided to have some kind of automated way to do this. I needed something that you could call that would put in the right rectangles in the right places with the right colours but was easy to manage, so I wrote a behavior. If you’re unfamiliar with Silverlight Behaviors (apologies for the American spelling, but that’s what they’re called) then read this post by Christian Schormann from the Blend team.

I realised that all I needed was something where I can specify which column I’m interested in, and what the start and end colours are. So this is the code I came up with:

/// <summary>
 /// A behaviour which targets a Grid to put background rectangles
 /// into column cells creating a gradient.
 /// </summary>
 public class GridGradientBehavior : Behavior<Grid>
   /// <summary>
   /// Somewhere to keep track of the items we've added to the grid
   /// </summary>
   List<Rectangle> rectangles = new List<Rectangle>();

   /// <summary>
   /// Called when this behaviour is attached to the grid.
   /// </summary>
   protected override void OnAttached()

     /// Just in case, clear any rectangles we've already put in
     foreach (var rect in rectangles)

       // Check the RowDefinitions. If there aren't any, just put in a single rectangle
       if (AssociatedObject.RowDefinitions == null
           || AssociatedObject.RowDefinitions.Count <= 1)
         InsertRectangle(new SolidColorBrush(StartColour), 0);
         // We need to interpolate between the two colours. I make use
         // of the SolidColorBrushInterpolator from System.Windows.Controls.DataVisualization
         // since my project already uses the toolkit.
         var interpolator = new SolidColorBrushInterpolator();
         interpolator.From = StartColour;
         interpolator.To = EndColour;
         interpolator.DataMinimum = 0;
         interpolator.DataMaximum = AssociatedObject.RowDefinitions.Count - 1;
         for (int i = 0; i < AssociatedObject.RowDefinitions.Count; i++)

     /// <summary>
     /// For each grid row, insert a rectangle of the appropriate colour into the ]
     /// appropriate row and column slot.
     /// </summary>
     /// <param name="color">The brush to use, interpolated between Start and End</param>
     /// <param name="i"></param>
     private void InsertRectangle(Brush color, int i)
       Rectangle rect = new Rectangle();
       rect.HorizontalAlignment = HorizontalAlignment.Stretch;
       rect.VerticalAlignment = VerticalAlignment.Stretch;
       rect.Fill = color;
       Grid.SetRow(rect, i);
       Grid.SetColumn(rect, Column);

       // This should ensure these rectangles are behind everything else in the grid
       Canvas.SetZIndex(rect, -1);

       // and if it doesn't, we insert our rectangles at the lowest point
       // in the visual tree
       AssociatedObject.Children.Insert(0, rect);

     /// <summary>
     /// Called when the behavior detaches. Remove all our rectangles from
     /// the grid.
     /// </summary>
     protected override void OnDetaching()
       foreach (var rect in rectangles)

     /// <summary>
     /// Dependency property telling us which column to apply this behaviour to
     /// </summary>
     public int Column
       get { return (int)GetValue(ColumnProperty); }
       set { SetValue(ColumnProperty, value); }
     public static readonly DependencyProperty ColumnProperty =
       DependencyProperty.Register("Column", typeof(int), typeof(GridGradientBehavior),
         new PropertyMetadata(0));

     /// <summary>
     /// Dependency property for the start colour of our gradient
     /// </summary>
     public Color StartColour
       get { return (Color)GetValue(StartColourProperty); }
       set { SetValue(StartColourProperty, value); }
     public static readonly DependencyProperty StartColourProperty =
       DependencyProperty.Register("StartColour", typeof(Color), typeof(GridGradientBehavior),
         new PropertyMetadata(Colors.White));

     /// <summary>
     /// Dependency property for the end colour of our gradient
     /// </summary>
     public Color EndColour
       get { return (Color)GetValue(EndColourProperty); }
       set { SetValue(EndColourProperty, value); }
     public static readonly DependencyProperty EndColourProperty =
       DependencyProperty.Register("EndColour", typeof(Color), typeof(GridGradientBehavior),
         new PropertyMetadata(Colors.Black));


The easiest way to apply this to a grid is to drag and drop it from the Behaviors section of the Assets pane. Then set the three parameters (StartColour, EndColour and Column) as appropriate. If (as in my example) you have two columns you want this to affect, you ust have to drop a second behavior onto the same grid.

There are a million ways you might want to extend this – letting you style rows instead of columns, or changing the rectangle to a border and having the ability to define different borders for top and bottom for example. Or you could use this to do alternating row colours. There’s quite a lot of scope for such a simple idea.

What I really want, though, is a way to get the same effect in an ItemsControl, but that’s a whole different problem.

Feel free to use this if it’s helpful.


Are Videogames Art?

The film critic Roger Ebert states they are not, and can never be. Ignoring the fact that he doesn’t play games himself, so couldn’t possibly experience any engagement that might indicate whether he’s right or not, one of his main points is that their interactive nature precludes videogames from ever being art. Could a game of Chess be considered art, he asks.

I think by making this assertion he’s actually missed something quite important, and to illustrate this, I have an example.

In the game Bioshock, your character is exploring a beautiful art-deco underwater city, having pitched up there after a plane crash. Note: This will contain major spoilers for the game. Please don’t continue if you haven’t played it and intend to at some time – the revelations are worth discovering on your own.

As you explore you (and the character you’re controlling) learn more about the city’s backstory, about the mysterious Andrew Ryan, who created the city, and about his social and biochemical attempts to create a perfect city.

The visual look of the game is fantastic, and wouldn’t disgrace any hollywood movie, but that’s not the reason I think it qualifies as art. Art isn’t about the quality of the rendering, or many modern artists wouldn’t qualify.

The true art in this game comes from its effect on you, the player (the audience, if you like) but I would argue that the effect it has on you is enhanced, rather than diminished, by the fact it is interactive. Here’s why.

Early on in the game, you meet a creepy little girl, known as a ‘Little Sister’. You learn that she’s been genetically engineered, and she stalks the city looking for dead people from whom she can extract a vital drug. The first time you meet one of these girls you’re told several things by the character who’s guiding your progress through the game:

  • They aren’t really little girls, because they’ve been enetically engineered
  • The drug they extract is something you need to improve your abilities within the game
  • To get hold of that drug you have to kill the little girl

At the same time, another character who you’ve never met before implores you not to harm the girl. She tells you:

  • You don’t have to kill her – you can ‘rescue’ her which frees her from the need to extract the drug
  • Rescuing her will still give you some of the drug she’s carrying, but not as much
  • If you rescue them, she will make sure you’re rewarded later (although she doesn’t specify how)

So as a player you have a clear choice: Kill what looks like a little girl for an instant reward, or rescue her, and hope that your future reward is worth it. Your ability to progress in the game wight well be affected by your decision – the game involves various weapons and abilities, some of which can become more powerful the more of the drug you get.

Now obviously, this is a game, a fairly violent one where you’ve already been killing plenty of other characters (think of ‘fast zombies’ from 28 days later for the kinds of enemies you have to kill) but this choice your given is very different. The game designers have very deliberately chosen to make these characters little girls, then offered you this choice of ways to play the game. (I don’t think you can also choose to do neither – to move past this point in the game, I think you have to choose, but later in the game you could choose to ignore the girls. But you have to make the choice at least once).

So as you play the rest of the game, each time you encounter a little sister, you make the same choice. When I played it, I always chose to rescue them.

The important thing here is that your choice has a profound effect on the ending of the game, which I’ll come to in a moment.

Much later in the game, there is a significant twist. You confront Andrew Ryan, and he reveals that the character you are playing as was actually born in the city, and was psychologically engineered to be controlled by a key phrase, and has been controlled by the character in the game who has, up to this point, been guiding you around the city, telling you where to go and what to do.

Then Ryan orders you to kill himself. With a golf club.

Which you do.

This is a fairly shocking moment, but interestingly, one over which you have no choice. The game is in a ‘cut scene’ at this point, and you have no control over what happens. Andrew Ryan is killed, by you, and you can’t stop it happening.

The first time I played this I thought I’d acidentally hit the ‘Fire’ button, and was horrified. I reloaded the game from an earlier point to check, but it all still happened the same way.

This is the first point in the game where I think the fact it’s a game makes it art. We’re used to killing or destroying things and people in games. But at this point, the designers chose not to give you a choice. The narrative happens regardless, and yet you feel shocked and culpable. This is a reaction which is amplified by it being a game. If you were seeing the same story play out in a linear form, it would still be a shocking moment, but your emotional reaction to it would be less. Or at least, different.

This is an example of being art because it’s a game, not despite.

And the second example, from the same game, is the ending.

Having killed Ryan, your game character is eventually freed from the psychological influence of Ryan’s nemesis, Frank Fontaine, and the last section requires you to fight him and kill him. Frankly, this is a typical ‘End of game Boss Level’ – you confront someone stronger than anyone you’ve previously encountered, and have to defeat them to complete the game. This is a convention of video games, almost like the ride into the sunset in cowboy movies, and is nothing remarkable until you finally overpower him. You then get the endgame.

And it’s different, depending on that choice you made early in the game. If you chose to rescue the little sisters, the game shows you one ending. After they’ve helped you kill Fontaine, one of the sisters approaches you, handing you something, and the following narration is spoken by the female doctor who looked after the sisters:

They offered you their city.

And you refused it.

And what did you do instead?

What I have come to expect of you.

You saved them.

You gave them the one thing that was stolen from them: A chance.

A chance to learn. To find love. To live.

And in the end what was your reward?

You never said, but I think I know.

A family.

It’s quite beautiful. I’m not ashamed to say, I cried at that ending. Someone once said that games could not be classed as art until you truly care about the characters, in which case, job done.

But I think this offers something slightly deeper. Because this ending is a direct response to your behaviour during the game. You only get this ending if you rescued the little sisters. You get a different ending (see previous link) if you harvested them, a far more prosaic ending (in my view).

But the truly interesting thing is that that happy ending is your ‘reward’. You’ve earned it. The game gives you this emotional response because of the way you’ve played it. No linear art form could do this – it’s only possible because a game is a thing to be played.

And that is why games can truly be art. Because they have a wholly unique way to affect you.

Silverlight Top Tip: Startup page for Navigation Apps

If you’re working on a Silverlight Navigation Framework application, you’ll often want to debug a specific page, rather than always start at your home page and navigate to it.

My previous solution was just to edit the Source attribute in the Frame, setting it to the initial Url I wanted. But this is dodgy, as if you forget to reset it before doing a release, your customers will end up confused.

The better way, which has only just occurred to me, is to change the default startup path in the associated Web application. In the Properties for your web application, choose the Web section, then edit the Start Action section, choose ‘Specific Page’ then edit the url. By default (in my app at least) it’s just set to the html page. I changed it like this:

Add #/<url> to your Specific Page urlAnd my app now starts up on the Advanced page.Just add whatever you want your initial start parameters to be – you can include query string params or anything else that would make a valid url.

Much safer.

Why does Visual Studio always break on user-handled exceptions?

I’ve been suffering this for ages. I can’t believe it’s taken this long to find the simple answer.

Does your Debug->Exceptions dialog box look like this?

Mine does. And when you want to debug and catch your exceptions in Silverlight, you have to check the ‘Thrown’ box next to Common Language Runtime Exceptions. Easy.

Except that now, the debugger will break on every single exception thrown while your app is running. Not just exceptions in your code that you’re not handling, but exceptions in the framework too. These are perfectly normal, and are all handled, but they are being caught before any handling code is executed.

This is particularly annoying when doing WebClient operations, or using Isolated Storage. You often get exceptions thrown when using these features, which are always handled before your code even sees them, but the debugger catches them anyway and stops.

I knew there was a way around this, because I’d seen it on other installations of Visual Studio. This is what the Exceptions dialog could look like:

With this, the debugger will only break on exceptions that aren’t handled elsewhere in your app. Which is what you usually want. I knew this option existed, but my Bing-Fu failed me, and I couldn’t find how to enable it. (Partly because I couldn’t remember what the extra column was called – if you search for user-unhandled you can find the answer).

You enable it in the Tools->Options dialog, in the Debugging section:

Just check ‘Enable Just My Code (Managed only)’ and magically, the Debug->Exceptions dialog will light up with the User-unhandled column.

I wish I knew this months ago.

Expression Blend 3 and Visual Studio 2010 RC

I installed VS2010 RC several weeks ago, and I’m now using it as my principal Silverlight dev environment. However, the sacrifice I made was that I could no longer use Blend 3 on my Silverlight 3 projects because the solution version number had changed.

I was wrong.

True, when you load your solution into Blend, it does complain that it’s a newer version, and might not work, but if you continue, Blend will successfully load a Silverlight 3 project. I tried two different projects, one which had been converted from VS2008 to VS2010 – which loaded properly – and one which I had created from scratch in VS2010. This one failed to load the web project, probably because VS2010 had created a .NET 4 web project, which Blend can’t load. But since Blend doesn’t care about the web project, this wouldn’t prove a problem.

So that’s useful – I can now use Blend again without resorting to weird hackery.

Of course, in just over a week, we might well have new versions of all the Silveright tools, as Mix10 opens in Las Vegas (I’ll be there!) and, if Microsoft follow their usual pattern, they’ll announce Silverlight 4 RTW. I think a lot of people will be disappointed if the tools aren’t available as soon as the announcement happens, although it won’t coincide with the RTM of Visual Studio 2010, because that launch isn’t scheduled until April (and that’s a launch, not necessarily the RTM date).

InvalidOperation_EnumFailedVersion when binding data to a Silverlight Chart

This one was a pain.

We’re releasing an analytics application in Silverlight to people inside the BBC. Today is release day, and we had some last-minute tweaks we wanted to roll out. Unfortunately, some of our customers were reporting a strange error when they tried this new version.

Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See


I could identify roughly where it was coming from from the stack trace, but the real pain was, this didn’t happen on my development machine, nor on any other machine in our immediate vicinity. But it happened on the machines of both our main stakeholders.

We narrowed it down to the version of the runtime. All the errors were happening on machines with version 3.0.40723.0 while I was running 3.0.40818.0 (and others in my department were running an even newer version).

The problem happened when binding data to a Silverlight Toolkit chart. It worked fine when using a pie chart, but we’d changed that chart to be a bar chart, which is when the errors appeared. Playing with it, Pie Charts work fine but Line, Bar or Column charts would throw this error.

The stack trace showed a lot of  NotifyDataContextChanged event handling before the error hit. The binding wasn’t complex. I’d set the chart’s DataContext to a list of keyvalue pairs, and set the BarSeries ItemsSource property to {Binding Mode=OneWay}.

To fix this (well, work around it, really) I stopped setting the DataContext of the chart in the code altogether, and in place of that, set the ItemsSource property of the BarSeries directly to the list of pairs. This worked fine, and seemed to avoid the error.

The really mysterious thing is why we never come across issues like this until we’re actually launching it? There’s clearly a Universal law at work.

<!–[if gte mso 9]> Normal 0 false false false EN-GB X-NONE X-NONE MicrosoftInternetExplorer4 <![endif]–><!–[if gte mso 9]> <![endif]–> <!–[endif]–>[InvalidOperation_EnumFailedVersion]
Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See

‘Cannot register duplicate name ‘XXX’ in this scope’ in VS 2010

Here’s a gotcha that was puzzling me yesterday.

I’ve just installed Visual Studio 2010 RC, and was trying it out on my current project. It’s a Silverlight Navigation-style project, but that’s not important to the bug.

I found one page where the Xaml designer wouldn’t handle the page properly – it was throwing exceptions, and the editor was showing an error in the Xaml. The line looked like this:

<local:SimpleConverter x:Name="SimpleConverter"/>

This is a value converter, designed to convert bindings from one type to another. The error it was showing was ‘Cannot register duplicate name ‘SimpleConverter’ in this scope’. This foxed me for a while – I thought perhaps because I was throwing exceptions when I didn’t recognise the type being converted, but even removing that and simplifying didn’t remove the error.

Then I noticed the key word in the error message: ‘Name’.

In Xaml you can use x:Name if you want something in the Xaml linked up to a class variable in your code-behind. But that was clearly causing issues with whatever the designer was doing behind the scenes. However, if you don’t need code-behind access (as I don’t in this case) you can use x:Key – and that’s the usual mechanism for naming resources.

Changing the resource to:

<local:SimpleConverter x:Key="SimpleConverter"/>

then the errors from the visual designer stop happening.

Of course, I’ve no idea if the errors are a bug in the designer, or if it’s just wrong to use x:Name in resources, but since I didn’t need the autowiring up of objects, it’s no problem to change it.