Showing posts with label Silverlight. Show all posts
Showing posts with label Silverlight. Show all posts

Sunday, 3 July 2011

Silverlight Music Rating App for KVR One Synth Challenge

After Spotify announced that you only got 10 hours free listening a month, I went in search of some new and interesting sources of music, and one of the things I stumbled across was the monthly KVR One Synth Challenge. Basically the idea is that you have to create an entire track using a single freeware virtual instrument – a different one each month. Despite this limitation, the quality of submissions is consistently impressive.

Voting is done by the community – you have to list your top five tracks. Each month I would download all the tracks and gradually eliminate them from a playlist, making notes on what I liked about each one as I went. This made me wonder if I could create a simple rating tool in Silverlight to help me do this – storing my comments and ratings, and allowing me to easily eliminate tracks from my shortlist.

So I created a simple application called “MusicRater”. At the moment the paths for each KVR OSC contest are hard-coded and I update it each month to point to the new one, but I have plans to make it more configurable in the future. The application makes use of my Silverlight star rating control.

Here’s a screenshot:

MusicRater

You can try it out here, and install it as an out of browser app if that is convenient for you. As of the time of posting, the version at this address is set up to return the tracks for OSC 29, which uses a synth called String Theory, which poses an interesting challenge to the contestants since it is a physical modelling synth. If you enjoy listening, make sure you head over to the voting thread and cast your votes.

Tuesday, 28 June 2011

How to Unit Test Silverlight Apps

I recently tried writing some unit tests for a Silverlight 4 project. The first barrier I ran into is that the typical way of creating unit tests – create a DLL, reference NUnit and your assembly to test, doesn’t work, since you can’t mix Silverlight assemblies with standard .NET assemblies.

The next hurdle is that fact that the Silverlight developer tools do not include a unit testing framework, and searching for Silverlight unit testing tools on the web can lead you down a few dead ends. It turns out that the thing you need is the Silverlight Toolkit. If you are just doing Silverlight 4, you only need the April 2010 toolkit.

Once this is installed, you get a template that allows you to add a “Silverlight Unit Test Application” to your project. This is a separate Silverlight application that contains a custom UI just to run unit tests.

Now you can get down to business writing your unit tests. You have to use the Microsoft unit testing attributes, i.e. [TestClass], [TestMethod], [TestInitialize]. You can also use the [Tag] attribute, which is the equivalent of NUnit’s [Category] to group your unit tests, allowing you to run a subset of tests easily.

It has a fairly nice GUI (though not without a few quirks) that displays the outcome of your tests for you, and allows you to copy the test results to your clipboard:

image

Unfortunately it doesn’t support Assert.Inconclusive (gets counted as a failure), but apart from that it works as expected.

Testing GUI Components

Another interesting capability that the Silverlight Unit Testing framework offers is that it can actually host your user controls and run tests against them.

Unfortunately some of the documentation that is out there is a little out of date, so I’ll run through the basics here.

You start off by creating a test class that inherits from the SilverlightTest base class. Then in a method decorated with the TestInitialize attribute, create an instance of your user control and add it to the TestPanel (a property on the base class, note that it has changed name since a lot of older web tutorials were written).

[TestInitialize]
public void SetUp()
{
    var control = new MyUserControl();
    this.TestPanel.Children.Add(control);
}

Note that if you don’t do this in the TestInitialize method and try to do it in your test method itself, the control won’t have time to actually load.

There is a nasty gotcha. If you user control uses something from a resource dictionary, then the creation of your control will fail in the TestInitialize method, but for some reason the test framework ploughs on and calls the TestMethod anyway, resulting in a confusing failure message. You need to get the contents of your app.xaml into the unit test application.

I already had my resource dictionaries split out into multiple files, which helped a lot. I added the resource xaml files to the test application as linked files, and then just referenced them as Merged dictionaries in my app.xaml:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="MarkRoundButton.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Now in your actual test method, you can now perform tests on your user control, knowing that it has been properly created and sized.

[TestMethod]
public void DisplayDefaultSize()
{
    Assert.IsTrue(tc.ActualWidth > 0);
}

There are also some powerful capabilities in there to allow you to run “asynchronous” tests, but I will save that for a future blog post as I have a few interesting ideas for how they could be used.

Monday, 13 June 2011

Silverlight Star Rating Control

I found myself needing a star rating control for a Silverlight application recently, and although I found a few open source ones, none of them worked quite how I wanted them to. Besides, I designed my own star shape in XAML a while ago and wanted to use that as the basis.

StarRating

In particular I wanted the ability to have half-star ratings. I thought at first it would require me to use some kind of complicated clipping construct, with a rectangle hidden behind my star, but I realised I could cheat by creating a half-star shape. Each star is a UserControl made up of three shapes – a star fill, a half star on top and then an outline on top.

I also wanted the colours to change as you hovered the mouse over it, indicating what rating would be given were you to click at any moment. This required the background of the control to be painted with a transparent brush, otherwise mouse events are only received while you are over stars and not in between them.

The biggest difficulty was making resize work. Path objects can be a pain to resize. I ended up putting them on a Canvas and using a ScaleTransform to get them the right size. All the brushes are customisable (six of them), plus you can change the number of stars, the line joins (pointy or round edged stars) and the line thicknesses. You can also turn off editing to simply display a star rating.

The Silverlight Star Rating Control is open source and available on CodePlex. The easiest way to install it is using NuGet.

To have a play with the star rating control, you can try it in my (rather chaotic looking) test harness below:

Monday, 6 June 2011

So … is Silverlight dead then?

Microsoft’s Windows 8 announcement has generated a surprising amount of controversy given that what was shown (a fancy new start menu that can be navigated using touch alone) was exactly what everyone was expecting. The only thing that could conceivably be described as a surprise was that Microsoft’s offering for the slate will be the “full” Windows OS, rather than the Windows Phone 7 OS adapted for a larger screen.

Apparently you will be able to make stuff for this new touch interface with HTML5 and JavaScript. Quite how that makes Silverlight dead I am not sure. I certainly don’t see any reason to panic. Given that it is full Windows, you will be able to write apps for it in VB6, Delphi or QBasic if you really want to. If you can’t write Windows 8 apps in Silverlight I’ll eat my hat. And if there is, as expected, a Windows 8 app store, you can be sure you’ll be able to sell Silverlight apps on it (in fact, if they base it on the Windows Phone app store, then Silverlight might even be the preferred/required dev platform).

I suppose it is possible that you won’t be able to make “tiles” using Silverlight (though they haven’t announced that you can’t), but I can’t get too worked up about that. I don’t want my applications consuming loads of memory and CPU cycles before I load them. Tiles should only be doing minimal processing.

Which brings us to the question everyone is asking. Is Silverlight dead?

When people call a technology “dead”, what they often really mean is “stable” and “mature”. I still develop WinForms apps on a daily basis. The API is effectively complete. It hasn’t had any meaningful new features for years. But it is a mature framework. It does what it does well enough, and if Microsoft were still actively trying to shoehorn new features into it that would be a bad thing. After a while, what is needed is not new features, but a new development paradigm.

WPF was, at first, that new paradigm, making it easy to do what was a nightmare in WinForms. And it followed a similar path to maturity. It’s got all the main capabilities you need to build impressive looking LOB apps. Microsoft got some things right with WPF, but like WinForms, it too has its limitations. I am not concerned that there isn’t a vast number of new features being announced for it every six months.

And guess what, Silverlight is on the same trajectory. Early releases picked up new capabilities at rapid pace. The fact it was chosen as the Windows Phone 7 dev platform has given it a new lease of life. But already it is reaching the stage where new versions are more incremental than revolutionary. That’s a good thing – the technology is approaching maturity.

To summarise: no need to panic. Keep building apps with the most appropriate technology that is available now. Those apps will continue to work just fine for years to come. Don’t worry that new technologies come along every few years that seem to “kill” older ones. I for one am glad that I am not currently developing using Visual Basic 16 or MFC version 23. And in 5 years time, I fully expect that there will be something even better than Silverlight to write Windows apps in. If there isn’t, it will be Microsoft, not Silverlight that is dead.

Wednesday, 10 November 2010

How to Invoke a Command on the ViewModel by Pressing the Enter Key in a TextBox with Silverlight and MVVM

I recently attempted to upgrade a WPF application to compile for Silverlight as well. One of the many issues I ran into was that in the WPF version, pressing the Enter key while I was in a TextBox caused the OK button I had on the form to be clicked by virtue of the fact that I could set the IsDefault property on the button. However, after porting to Silverlight, that no longer worked, since the IsDefault property is missing..

A web-search revealed that someone had made a “behavior” that allows a specified button to be clicked when you press Enter within a TextBox (available for download here). However, it had one big problem: at the point that the command fired in my ViewModel, the value bound to the textbox contents had not been updated, since the textbox had not lost focus.

The original WPF binding I had an UpdateSourceTrigger ensuring that the ViewModel was always kept up to date with what was in the TextBox:

<TextBox Text="{Binding Answer, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

but in Silverlight, the PropertyChanged UpdateSourceTrigger is not available, so  I was left with the following:

<TextBox Text="{Binding Answer, Mode=TwoWay}" />

I decided to make my own EnterKeyCommand binding that would allow you to specify for a TextBox which command on the ViewModel should be run. Here’s the code:

public static class EnterKeyHelpers
{
    public static ICommand GetEnterKeyCommand(DependencyObject target)
    {
        return (ICommand)target.GetValue(EnterKeyCommandProperty);
    }

    public static void SetEnterKeyCommand(DependencyObject target, ICommand value)
    {
        target.SetValue(EnterKeyCommandProperty, value);
    }

    public static readonly DependencyProperty EnterKeyCommandProperty =
        DependencyProperty.RegisterAttached(
            "EnterKeyCommand",
            typeof(ICommand),
            typeof(EnterKeyHelpers),
            new PropertyMetadata(null, OnEnterKeyCommandChanged));

    static void OnEnterKeyCommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
    {
        ICommand command = (ICommand)e.NewValue;
        FrameworkElement fe = (FrameworkElement)target;
        Control control = (Control)target;
        control.KeyDown += (s, args) =>
        {
            if (args.Key == Key.Enter)
            {
                // make sure the textbox binding updates its source first
                BindingExpression b = control.GetBindingExpression(TextBox.TextProperty);
                if (b != null)
                {
                    b.UpdateSource();
                }
                command.Execute(null);
            }
        };
    }
}

Most of it is pretty simple, and it will allow an Enter key command to be specified for any control, not just textboxes. However, if you have bound to a textbox, it will call UpdateSource on any Text binding you have made, to ensure your ViewModel operates on the latest data.

Here’s how you use it in XAML:

<TextBox 
    Text="{Binding Answer, Mode=TwoWay}" 
    my:EnterKeyHelpers.EnterKeyCommand="{Binding SubmitAnswerCommand}"/>

It also has the advantage of being considerably more succinct than the equivalent XAML for using the behavior I linked to earlier.

Friday, 29 October 2010

MVVM – Is it Worth the Pain?

After finding it very easy to get MVVM working in WPF with IronPython, I thought it would be trivial to achieve the same thing in Silverlight. Unfortunately, my bindings didn’t work at all after porting a simple game to Silverlight. The problem may have something to do with the issues described in this blog post, but since I needed to demo my code for a local user group event, I abandoned MVVM and went back to just talking directly to the controls from within my ViewModel, which worked perfectly, and simplified my code considerably. It made me wonder why I was using MVVM in the first place.

The Pain of MVVM

I jumped on the bandwagon fairly early and have been writing the majority of my WPF and Silverlight code using MVVM. But to be honest, it has not been plain sailing. There is a real elegance to it that I like, and I love the testability, but there have been plenty of pain points.

For example, triggering animations and discovering when they have finished from the ViewModel has been a nightmare. I’ve tried various solutions, finding one that works with Silverlight and one with WPF but none that work with both, and have managed to crash Visual Studio dozens of times in the process.

Even simple things like setting the focus to the appropriate controls requires a rather convoluted system of “behaviours”, to do something that is a single line of code with access to the controls themselves. And every time I create a behaviour I seem to spend ages debugging my dependency properties, trying to work out why they aren’t doing what I expected.

The Purpose of MVVM

So if MVVM is so painful for non-trivial applications, why use it at all? What’s the point of MVVM? I think there are three answers.

1. Testability

The first driver for using MVVM is testability. If we put our logic in the C# “code-behind” of a XAML class, then running unit tests on that logic becomes very difficult. But with IronPython, that consideration is irrelevant. Since it is a dynamic language, and we are not using “code-behind” in any case, my non-MVVM version of my ViewModel is just as testable as the one that used data binding exclusively.

2. Data Binding

The second motivation for using MVVM is that the pattern encourages the use of data binding, and simplifies it considerably by removing the need for data converters or complicated binding expressions. But why is data-binding to a TextBox better than just getting or setting its Text property?

One of the key benefits of data-binding comes when we want to bind the same thing to more than one property. A Command object is a good example. One Command object could be bound to a drop-down menu and a toolbar button. So setting the Command’s IsEnabled state can be used to enable and disable both views. But most of the time, binding is a one-to-one relationship.

Data binding also saves a bunch of code in CRUD type applications where you are binding directly to properties on an existing model type, but I don’t tend to write applications like that anyway. I think you can use it to make magical things happen with input validation too, but again, it’s not something I’ve ever needed.

3. Designability

The third driver behind MVVM is the goal of designer / developer separation. The idea is that a designer can create a XAML file and bind it to test data, and then the developer can come along and create the real DataContext at a later date. The idea certainly sound impressive, but I can’t help but think that the designer will run into all the problems mentioned above if he actually wants to give his XAML GUI a real workout. And the truth is that I’ve never worked with a designer writing XAML and will not be doing so in the foreseeable future. The graphic designers we use send us bitmaps and Flash mockups.

A Hybrid Approach

I am now wondering whether I should think of my ViewModel more as a “Presenter”. It could still be the DataContext of the object defined in XAML to enable data-binding where required, but it would also have access directly to any properties on that XAML object. For testability in statically typed languages, you could define an interface with methods like StartAnimation or SetFocusToTextBox – a little cumbersome perhaps, but probably no more so than the hoops you have to jump through to make these things happen from your ViewModel using nothing but data binding.

Anyway, looks like I’m not alone in questioning MVVM. Here’s a good post from K Scott Allen. What do you think? Does MVVM fail a cost-benefit analysis for the types of application you work on?

Thursday, 28 October 2010

Creating Silverlight Apps with IronPython

Using IronPython to create Silverlight applications is a little different from using C#. With C# you are building a .xap file, which contains all the compiled code for your application. However, in IronPython, the recommended way is not to create a .xap file at all. Instead you simply write Python script in your HTML page, or in .py files hosted on your web server.

Getting Started

The easiest way to get started is by using the latest IronPython (currently 2.7 beta 1) which comes with Visual Studio 2010 integration. This enables you to simply create a new “IronPython Silverlight Web Page” project. However, don’t worry if you don’t have or want to use VS2010 – the process is almost the same without it.

When you create your new Silverlight project, it creates two files for you. The first is a simple HTML page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript">
        window.DLR = { settings: { console: true } }
    </script>
    <script src="http://gestalt.ironpython.net/dlr-latest.js" type="text/javascript"></script>
    <title>SilverlightPage1</title>
</head>
<body>
    <input id="Button1" type="button" value="Say, Hello!" />
    <script type="text/python" src="SilverlightPage1.py"></script>
</body>
</html>

Including the DLR

There are a few interesting points of note in the <head> section of this page. First is the dlr-latest.js script file. This is all that is needed to enable python (and xaml) scripting directly in HTML. The settings: { console: true } section enables a very cool debugging feature in your web page, whereby you get an IronPython interactive interpreter that you can pop up from the bottom of your web page:

IronPython Interactive Interpreter

Running a .py Script

Then we have the Python script itself. The project template includes a Python file containing some basic code to subscribe to the button onclick event and show an alert.

def SayHello(s,e):
    window.Alert("Hello, World!")
document.Button1.events.onclick += SayHello

Embedding Python in the HTML

There is in fact no need for our Python script to be in a .py file if we don’t want to. We can put Python code directly in the HTML inside a <script> block if we want:

<body>
    <input id="Button1" type="button" value="Say, Hello!" />
    <script type="text/python">
    def SayHello(s,e):
        window.Alert("Hello from HTML")
 
    document.Button1.events.onclick += SayHello
    </script>
</body>

Running the Page

When you run the page from Visual Studio, it starts the “Chiron Development Server” to host your page. You don’t need this to develop for IronPython, but one thing I discovered is that you do need the MIME type to be set up correctly for .py files. For example, if you are using WebMatrix you need to put a web.config file in your application root folder with the following content:

<configuration>
    <system.webServer>
        <staticContent>
            <mimeMap fileExtension=".py" mimeType="text/python" />
        </staticContent>
    </system.webServer>
</configuration>

Sadly I couldn’t work out a way of getting Visual Studio to break on specific lines of Python script despite trying attaching to Chiron and to my Web Browser. I guess it may be possible to step through the script with a debugger for the browser, but I haven’t tried that yet.

Using XAML

Obviously XAML is very important for Silverlight applications and it is very easy to use with the DLR. We can start by adding a simple XAML file to our project. Annoyingly, the Visual Studio add item dialog filters out all the templates except the IronPython ones. Hopefully that will be fixed in a future release.

We’ll create a MainForm.xaml file with the following basic content:

<UserControl 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel Background="BurlyWood">
        <TextBlock Margin="5" Text="Enter your name:"/>
        <TextBox Margin="5" x:Name="textBoxName"/>
        <Button Margin="5" x:Name="buttonOK" Content="OK" />
    </StackPanel>
</UserControl>

Now in our HTML page, all that is needed is to specify the XAML and the size of the Silverlight object that will host it:

<script id="MainForm" type="application/xml+xaml" width="200" height="100" src="MainForm.xaml"></script>

As before, there is no need for the XAML to be in a separate file. We can put it directly within the script block if needed. Here’s our app running:

IronPython Silverlight App

Now suppose we want to write some Python code to run when the OK button is clicked instead of the “Say, Hello!” button. We can use Python script in the way already shown, but need to mark the <script> tag with class=”MainForm” in order to ensure that it runs against the correct Silverlight object that contains our MainForm UserControl. This is because the DLR supports multiple Silverlight controls on your page at a time, and by default will create a new one for each xaml script. The xaml variable is pre-loaded with the root element of the loaded xaml – in our case, a UserControl.

<script class="MainForm" type="text/python">
def SayHello(s,e):
    window.Alert("Hello " + xaml.textBoxName.Text)

xaml.buttonOK.Click += SayHello
</script>

Now when we run this, it works (sort of). In FireFox, the alert appears but you have to wait several minutes before it lets you click on it. I have no idea why. IE8 works OK so long as you are running against the latest gestalt (otherwise the xaml is None so the subscription to the button click event fails).

Going Further

Obviously this only covers the absolute basics. Visit http://www.ironpython.net/ironpython/browser/ for more documentation and instructions. I may blog a bit more on this at a later date.

Tuesday, 15 September 2009

Checking MIME type for cross domain Silverlight hosting

I recently ran into some problems trying to embed a Silverlight application in a web page hosted on another server. It seems that to do so, you must have your MIME type for .xap files correctly configured (should be application/x-silverlight-app). Interestingly, this is not required if you are hosting the .xap file in a web page on the same domain.

Unfortunately for me, my shared Linux hosting provider allows no way of configuring or even viewing the MIME types. After searching in vain for a utility that would let me have a look and see what MIME type a given URL was returning, I wrote my own test function. It turns out to be possible in just two lines of code – create a WebRequest, and examine the ContentType of the WebResponse.

[TestFixture]
public class MimeTypeChecker
{
    [Test]
    public void CheckSilverlightMimeTypeIsCorrect()
    {
        string mimeType = GetMimeType("http://www.mydomain.com/mysilverlightapp.xap");
        Assert.AreEqual("application/x-silverlight-app", mimeType);
    }

    public string GetMimeType(string url)
    {
        WebRequest request = WebRequest.Create(url);
        WebResponse response = request.GetResponse();
        return response.ContentType;
    }
}

Update: If your .xap file is hosted on an Apache server on Linux, you can set up the MIME types correctly by creating a .htaccess file. This can be put in the root of your hosting space, or just in the folder containing the .xap file. It only needs the .xap registration, but the example I show below configures xaml and xbap as well:

AddType application/x-silverlight-app .xap
AddType application/xaml+xml .xaml
AddType application/x-ms-xbap .xbap

Tuesday, 6 January 2009

XAML SoundWave Take 2

In my previous post, I described a couple of options for creating a sound-wave icon graphic in XAML. While my final solution worked OK, I have since thought up an even simpler approach by using the XAML Path mini-language.

The reason I didn’t initially go for this option was that I didn’t want to calculate the coordinates of each point. However, we can draw the shape rotated by 45 degrees first, which allows us to put each point nicely on a grid, and then use a RotateTransform afterwards to put it back.

The XAML Path is a very useful tool to master if you prefer to work directly with XAML instead of using a design tool like Expression Blend. Here’s the first path, to create a quadrant shape:

<Path Fill="Orange" Data="M 0,0 h 1 a 1,1 90 0 1 -1,1 Z" />

The M command starts us off by moving to the specified coordinates (0,0 in this case). A lower case h means a relative horizontal line – we move one unit to the right. Now the lower case a command means we are drawing an arc using relative coordinates. The first two arguments are the radius of the arc (1,1 = circle of radius 1), then comes the angle in degrees (90), then a flag indicating if this is a large arc – in our case, no (0), and then another flag indicating if we are going clockwise (1 = yes). Finally, we put the end coordinates (-1,1) which are relative to the starting point because we used a lower case a. This path is then closed with the Z command although this is not strictly necessary for us as we are not using a Stroke brush on this Path.

Now we can draw the other three sections, each of which consists of a horizontal line followed by an arc, then a vertical line, and finally another arc with a smaller radius. I don’t bother with the Z because I have reached my starting point again with the second arc.

<Path Fill="Orange" Data="M 2,0 h 1 a 3,3 90 0 1 -3,3 v -1 a 2,2 90 0 0 2,-2" />
<Path Fill="Orange" Data="M 4,0 h 1 a 5,5 90 0 1 -5,5 v -1 a 4,4 90 0 0 4,-4" />
<Path Fill="Orange" Data="M 6,0 h 1 a 7,7 90 0 1 -7,7 v -1 a 6,6 90 0 0 6,-6" />

We end up with the right graphics but with the wrong orientation:

image

A RotateTransform (plus a ScaleTransform) allows us to put this exactly how we want it:

image

Here’s the complete XAML:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Background="#E0E0E0">
  <Grid Width="8" Height="8">
    
    <Grid.RenderTransform>
      <TransformGroup>
      <ScaleTransform ScaleX="10" ScaleY="10" />
      <RotateTransform Angle="-45" />
      </TransformGroup>
    </Grid.RenderTransform>
    
    <Path Fill="Orange" Data="M 0,0 h 1 a 1,1 90 0 1 -1,1 Z" />
    <Path Fill="Orange" Data="M 2,0 h 1 a 3,3 90 0 1 -3,3 v -1 a 2,2 90 0 0 2,-2" />
    <Path Fill="Orange" Data="M 4,0 h 1 a 5,5 90 0 1 -5,5 v -1 a 4,4 90 0 0 4,-4" />
    <Path Fill="Orange" Data="M 6,0 h 1 a 7,7 90 0 1 -7,7 v -1 a 6,6 90 0 0 6,-6" />
  </Grid>
</Page>

Saturday, 8 November 2008

Model View View-Model (MVVM) in Silverlight

I watched an excellent screencast by Jason Dolinger recently, showing how to implement the Model View View-Model pattern in WPF. A lot of the documentation on the MVVM pattern seems unnecessarily complicated, but Jason's demonstration explains it very clearly.

The basic idea of MVVM is that we would like to use data binding to connect our View to our Model, but data binding is often tricky because our model doesn't have the right properties. So we create a View Model that is perfectly set up to have just the right properties for our View to bind to, and gets its actual data from the Model.

To try the technique out I decided to refactor a small piece of a Silverlight game I have written, called SilverNibbles, which is a port of the old QBasic Nibbles game, keeping the graphics fairly similar. At the top of the screen there is a scoreboard, whose role it is to keep track of the scores, number of lives, level, speed etc. This is the piece I will attempt to modify to use MVVM.

SilverNibbles Scoreboard

Let's have a look at the original code-behind for the Scoreboard user control. As you can see, there is a not lot going on here. Whenever a property on the Scoreboard is set, the appropriate changes are made to the graphical components. This is very similar to the typical code that would be written for a Windows Forms user control.

using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverNibbles
{
    public partial class Scoreboard : UserControl
    {
        private int players;
        private int level;
        private int speed;
        private int jakeScore;
        private int sammyScore;

        public Scoreboard()
        {
            InitializeComponent();
        }

        public int Players
        {
            get 
            {
                return players; 
            }
            set 
            {
                players = value;
                jakeLives.Visibility = players == 2 ? Visibility.Visible : Visibility.Collapsed;
                jakeScoreLabel.Visibility = players == 2 ? Visibility.Visible : Visibility.Collapsed;
                jakeScoreTextBlock.Visibility = players == 2 ? Visibility.Visible : Visibility.Collapsed;
            }
        }

        public int Level
        {
            get
            {
                return level;
            }
            set
            {
                level = value;
                levelTextBlock.Text = value.ToString();
            }
        }

        public int Speed
        {
            get
            {
                return speed;
            }
            set
            {
                speed = value;
                speedTextBlock.Text = value.ToString();
            }
        }

        public int SammyScore
        {
            get
            {
                return sammyScore;
            }
            set
            {
                sammyScore = value;
                sammyScoreTextBlock.Text = value.ToString();
            }
        }

        public int JakeScore
        {
            get
            {
                return jakeScore;
            }
            set
            {
                jakeScore = value;
                jakeScoreTextBlock.Text = value.ToString();
            }
        }

        public int JakeLives
        {
            get
            {
                return jakeLives.Lives;
            }
            set
            {
                jakeLives.Lives = value;
            }
        }

        public int SammyLives
        {
            get
            {
                return sammyLives.Lives;
            }
            set
            {
                sammyLives.Lives = value;
            }
        }
    }
}

Instead of having all these properties, the Scoreboard will become a very simple view. Now the code-behind of Scoreboard is completely minimalised:

namespace SilverNibbles
{
    public partial class Scoreboard : UserControl
    {
        public Scoreboard()
        {
            InitializeComponent();
        }
    }
}

Now it is the job of whoever creates Scoreboard to give it a ScoreboardViewModel as its DataContext. It doesn't even have to be a ScoreboardViewModel either, so long as it has the appropriate properties. This means that a graphic designer could use an XML file instead to create dummy data to help while designing the appearance. Here's my code elsewhere in the project that sets up the data context of the Scoreboard with its View Model.

scoreData = new ScoreboardViewModel();
scoreboard.DataContext = scoreData;

Now I simply modify the scoreData object's properties, and the Scoreboard will update its view automatically.

What has changed in the Scoreboard user control's XAML? Well first, it has Binding statements for every property that gets its value from the view model. I was also able to remove all the x:Name attributes from the markup, which is a sign that MVVM has been done right. I also needed to make my Lives property on my LivesControl user control into a dependency property to allow it to accept the binding syntax as a value.

<UserControl x:Class="SilverNibbles.Scoreboard"
    xmlns="http://schemas.microsoft.com/client/2007" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:sn="clr-namespace:SilverNibbles"
     >
    <Grid x:Name="LayoutRoot" Background="LightYellow" ShowGridLines="False">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="20*" />
            <ColumnDefinition Width="35*" />
            <ColumnDefinition Width="25*" />
            <ColumnDefinition Width="10*" />
        </Grid.ColumnDefinitions>
        
        <!-- row 0 -->
        <TextBlock 
            Grid.Row="0" 
            Grid.Column="0"
            Text="High Score" 
            FontSize="18"
            FontFamily="teen bold.ttf#Teen" />
        <TextBlock 
            Grid.Row="0" 
            Grid.Column="1"
            Margin="5,0,5,0"
            Text="{Binding Record}" 
            FontSize="18"
            FontFamily="teen bold.ttf#Teen" />
        
        <TextBlock 
            Grid.Column="2" 
            Text="Level" 
            HorizontalAlignment="Right" 
            Margin="5,0,5,0"
            FontSize="18"
            FontFamily="teen bold.ttf#Teen" />
        <TextBlock 
            Grid.Column="3" 
            Margin="5,0,5,0"
            Text="{Binding Level}" 
            FontSize="18"
            FontFamily="teen bold.ttf#Teen" />
                
        <!-- row 1 -->        
        <TextBlock 
            Grid.Row="1"
            Text="Sammy" 
            FontSize="18"
            FontFamily="teen bold.ttf#Teen" />
       <sn:LivesControl
            Grid.Row="1"
            Grid.Column="1"
            HorizontalAlignment="Right"
           Fill="{StaticResource SammyBrush}"
           Lives="{Binding SammyLives}"
             />        
       <TextBlock 
            Grid.Row="1"
            Grid.Column="1"
            Margin="5,0,5,0"
            Text="{Binding SammyScore}" 
            FontSize="18"
            FontFamily="teen bold.ttf#Teen"
            />
        
       <TextBlock 
           Grid.Row="1" 
           Grid.Column="2" 
            Text="Speed" 
            HorizontalAlignment="Right" 
            Margin="5,0,5,0"
            FontSize="18"
            FontFamily="teen bold.ttf#Teen"
           />
        <TextBlock 
            Grid.Row="1"
            Grid.Column="3" 
            Margin="5,0,5,0"
            Text="{Binding Speed}" 
            FontSize="18"
            FontFamily="teen bold.ttf#Teen"
            />
        
        <!-- row 2 -->
        <TextBlock 
            Grid.Row="2"
            Grid.Column="0"
            Text="Jake" 
            FontSize="18"
            FontFamily="teen bold.ttf#Teen"
            Visibility="{Binding JakeVisible}"            
            />
        <sn:LivesControl
            Grid.Row="2"
            Grid.Column="1"
            HorizontalAlignment="Right"
            Fill="{StaticResource JakeBrush}"
            Visibility="{Binding JakeVisible}"
            Lives="{Binding JakeLives}"
             />
       <TextBlock 
            Grid.Row="2"
            Grid.Column="1"
            FontSize="18"
            Margin="5,0,5,0"
            Text="{Binding JakeScore}" 
            FontFamily="teen bold.ttf#Teen"
            Visibility="{Binding JakeVisible}"
           />
    </Grid>
</UserControl>

Here's what my ScoreboardViewModel looks like. The main thing to notice is that I have implemented the INotifyPropertyChanged interface. I rather lazily raise the changed event every time the setter is called irrespective of whether the value really changed. Notice also I have created a JakeVisible property. This highlights how the View Model can be used to create properties that are exactly what the View needs.

namespace SilverNibbles
{
    public class ScoreboardViewModel : INotifyPropertyChanged
    {
        private int players;
        private int level;
        private int speed;
        private int jakeScore;
        private int sammyScore;

        public int Players
        {
            get
            {
                return players;
            }
            set
            {
                players = value;
                RaisePropertyChanged("Players");
                RaisePropertyChanged("JakeVisible");
            }
        }

        public Visibility JakeVisible
        {
            get
            {
                return players == 2 ? Visibility.Visible : Visibility.Collapsed;
            }
        }

        public int Level
        {
            get
            {
                return level;
            }
            set
            {
                level = value;
                RaisePropertyChanged("Level");
            }
        }

        public int Speed
        {
            get
            {
                return speed;
            }
            set
            {
                speed = value;
                RaisePropertyChanged("Speed");
            }
        }

        public int SammyScore
        {
            get
            {
                return sammyScore;
            }
            set
            {
                sammyScore = value;
                RaisePropertyChanged("SammyScore");
            }
        }

        public int JakeScore
        {
            get
            {
                return jakeScore;
            }
            set
            {
                jakeScore = value;
                RaisePropertyChanged("JakeScore");
            }
        }

        int jakeLives;
        int sammyLives;

        public int JakeLives
        {
            get
            {
                return jakeLives;
            }
            set
            {
                jakeLives = value;
                RaisePropertyChanged("JakeLives");
            }
        }

        public int SammyLives
        {
            get
            {
                return sammyLives;
            }
            set
            {
                sammyLives = value;
                RaisePropertyChanged("SammyLives");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }
    }
}

I think there are alternatives to using INotifyPropertyChanged such as creating dependency properties or inheriting from DependencyObject. I don't know what the advantages or disadvantages of taking that approach would be. That is something for a future investigation.

There are lots of other parts of the SilverNibbles application that could be refactored to use this pattern, but that is also a task for another day. View the code at CodePlex, and play SilverNibbles here.

Tuesday, 14 October 2008

Styling a ListBox in Silverlight 2

Back in April, I started a series of posts here on how to completely customise the style of a ListBox in Silverlight 2 beta 1, including the scroll-bar styles. That was followed by a rather painful update to Silverlight 2 beta 2 (see Part 1, Part 2, Part 3). Now that Silverlight 2 has officially shipped, the code required one last update. Thankfully the changes were not so great this time. A few deprecated properties needed to be removed from the XAML, and some Duration attributes needed to be changed to GeneratedDuration, but that was about it.

There is some good news. From initial inspection it looks like the scroll-bar bug, where you saw a stretched horizontal scroll-bar behind your vertical scroll-bar has finally been fixed. And first impressions of the XAML preview in Visual Studio are good - you can actually see what it looks like without having to run the project.

What it hasn't fixed is my appalling colour selections and graphical design skills. I might take the time to work a bit more on the appearance of this thing now that I can be sure the syntax isn't going to change yet again.

Fully Styled Listbox in Silverlight 2

I've uploaded my example project which can be opened in Visual Studio 2008 (with Silverlight Tools) or in Expression Blend 2 SP1. Download it here.

Saturday, 12 July 2008

Styling a ListBox with Silverlight 2 Beta 2 (Part 3) - ListBoxItem Style

This is the third and final part of my updated series on how to style a ListBox in Silverlight 2 Beta 2. Here are the links to part 1 and part 2.

So far we have customised the appearance of a ListBox, including the ScrollBars. The one remaining missing piece is some kind of indication of which items are selected, and visual feedback when the mouse hovers over a ListBox item.
To achieve this we need to add some Storyboards to the custom ListBoxItem we created in my first post. There are eight states you can specify Storyboards for. The most important for our purposes are "Normal", "Selected", and "MouseOver". Note that we need to use two Visual State Groups. One will define Normal and MouseOver, while the other will define Selected and Unselected. This gives us the flexibility to combine animations if we require to show combined states such as Selected and MouseOver.

Unfortunately it can also mean conflict of interests. With the beta 1 model, I quite easily specified one colour for Normal, one colour for Selected and one colour for MouseOver. However, with the new model, the MouseOver and Unselected states compete to set the background colour. The solution I eventually came up with was to have two borders and control their opacity (partly inspired by this forum post). One border is used to show MouseOver state, and the other to show Selected state. Here is the updated ListBoxItem style containing the new border elements (without Visual State Groups):

<Style x:Key="ListBoxItemStyle1" TargetType="ListBoxItem"
    xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows">
  <Setter Property="Foreground"
      Value="{StaticResource ListBoxItemForegroundBrush}" />
  <Setter Property="Template">
  <Setter.Value>
  <ControlTemplate TargetType="ListBoxItem">
  <Grid x:Name="Root">
    <vsm:VisualStateManager.VisualStateGroups>
       ...
    </vsm:VisualStateManager.VisualStateGroups>
  
    <Border CornerRadius="5" Margin="1"
      x:Name="HoverBorder">
      <Border.Background>
        <SolidColorBrush
        x:Name="HoverBorderBackgroundBrush"
        Color="#51615B" />
      </Border.Background>
    </Border>
    <Border CornerRadius="5" Margin="1"
      x:Name="SelectedBorder">
      <Border.Background>
        <SolidColorBrush
        x:Name="SelectedBorderBackgroundBrush"
        Opacity="0"
        Color="#397F8F" />
      </Border.Background>
    </Border>
    <ContentPresenter
        Margin="4,1"                  
        Content="{TemplateBinding Content}"
        Foreground="{TemplateBinding Foreground}" />
    </Grid>                      
    </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

I have chosen to prioritise the Selected background above the MouseOver background, but you can easily change that by swapping the order of the borders.

The VisualStateGroups specify the two ColorAnimations I need - one for Selected and one for MouseOver. I also needed to add a DoubleAnimation for the opacity of the SelectedBorder.

<vsm:VisualStateManager.VisualStateGroups>

<vsm:VisualStateGroup x:Name="SelectionStates">
<vsm:VisualState x:Name="Unselected" />
<vsm:VisualState x:Name="Selected">
  <Storyboard>
    <DoubleAnimation
     Storyboard.TargetName="SelectedBorderBackgroundBrush"
     Storyboard.TargetProperty="Opacity"
     Duration="0"
     To="1.0"/>
   <ColorAnimation
     Storyboard.TargetName="SelectedBorderBackgroundBrush"
     Storyboard.TargetProperty="Color"
     Duration="0"
     To="#FF397F8F"/>
  </Storyboard>
</vsm:VisualState>
</vsm:VisualStateGroup>

<vsm:VisualStateGroup x:Name="CommonStates">
<vsm:VisualState x:Name="Normal" />
<vsm:VisualState x:Name="MouseOver">
  <Storyboard>
    <ColorAnimation
      Storyboard.TargetName="HoverBorderBackgroundBrush"
      Storyboard.TargetProperty="Color"
      Duration="0"
      To="#898A8A"/>
  </Storyboard>
</vsm:VisualState>
</vsm:VisualStateGroup>
</vsm:VisualStateManager.VisualStateGroups>

Here's what it looks like (item 3 selected, item 5 mouse over):

Silverlight 2 ListBox Style with Mouse Over and Selected Item

OK, so my choice of colours is awful and there are lots of visual elements that could be improved (and we still await a fix for the vertical scrollbar bug), but hopefully I have demonstrated how it is possible to completely change every visual element of how your ListBox is rendered in Silverlight 2 beta 2.
I have uploaded my test project here which you can load in Expression Blend 2.5 or Visual Studio 2008.

Saturday, 21 June 2008

Styling a ListBox With Silverlight 2 Beta 2 (Part 2) - Scrollbars

In my first post, I explained how to create a very basic ListBox and ListBoxItem style that governed the appearance of a ListBox. It is still very rudimentary though, and doesn't give any visual feedback of selected items or mouse over. It also doesn't have any scrollbars. Here's what we have so far (with a few changes to the colours - although I'm not sure it's an improvement!):

image2

Adding scrollbars is actually quite simple. All we need to do is add a ScrollViewer to our ListBox style.

<Border Padding="3" Background="#E6BB8A" CornerRadius="5">
   <ScrollViewer x:Name="ScrollViewer"
       Padding="{TemplateBinding Padding}">
       <ItemsPresenter />
   </ScrollViewer>
</Border>

Which gives us scrollbars:

image3

Unfortunately, as nice as the default scrollbars look, they do not fit at all with the visual theme of our ListBox. We need another style which we will base on the default ScrollViewer style.

Here's the ScrollViewer template, slightly customised to remove the border and the square in the bottom right-hand corner. It looks a little intimidating because I left in most of the stuff from the default ScrollViewer style. We could have got rid of a lot of it, but as we are not planning to customise this part very much, we will leave it in there.

<Style TargetType="ScrollViewer" x:Key="ScrollViewerStyle1">
   <Setter Property="IsEnabled" Value="true" />
   <Setter Property="Foreground" Value="#FF000000" />
   <Setter Property="BorderBrush" Value="#FFA4A4A4" />
   <Setter Property="BorderThickness" Value="1" />
   <Setter Property="HorizontalContentAlignment" Value="Left" />
   <Setter Property="VerticalContentAlignment" Value="Top" />
   <Setter Property="Cursor" Value="Arrow" />
   <Setter Property="TextAlignment" Value="Left" />
   <Setter Property="TextWrapping" Value="NoWrap" />
   <!-- Cannot currently parse FontFamily type in XAML so it's being set in code -->
   <!-- <Setter Property="FontFamily" Value="Trebuchet MS" /> -->
   <Setter Property="FontSize" Value="11" />
   <Setter Property="VerticalScrollBarVisibility" Value="Visible" />
   <Setter Property="Template">
       <Setter.Value>
           <ControlTemplate TargetType="ScrollViewer">
               <Grid Background="{TemplateBinding Background}">
                   <Grid.ColumnDefinitions>
                       <ColumnDefinition Width="*"/>
                       <ColumnDefinition Width="Auto"/>
                   </Grid.ColumnDefinitions>
                   <Grid.RowDefinitions>
                       <RowDefinition Height="*"/>
                       <RowDefinition Height="Auto"/>
                   </Grid.RowDefinitions>
                   <!-- Fill="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" -->
                   <ScrollContentPresenter
                     x:Name="ScrollContentPresenter"
                     Grid.Column="0"
                     Grid.Row="0"
                     Content="{TemplateBinding Content}"
                     ContentTemplate="{TemplateBinding ContentTemplate}"
                     Cursor="{TemplateBinding Cursor}"
                     Background="{TemplateBinding Background}"
                     HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                     TextAlignment="{TemplateBinding TextAlignment}"
                     TextDecorations="{TemplateBinding TextDecorations}"
                     TextWrapping="{TemplateBinding TextWrapping}"
                     VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
                     Margin="{TemplateBinding Padding}" />
                   <ScrollBar
                     x:Name="VerticalScrollBar"
                     Grid.Column="1"
                     Grid.Row="0"
                     Orientation="Vertical"
                     Cursor="Arrow"
                     Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}"
                     ViewportSize="{TemplateBinding ViewportHeight}"
                     Minimum="0"
                     Maximum="{TemplateBinding ScrollableHeight}"
                     Value="{TemplateBinding VerticalOffset}"
                     Width="18"/>
                   <ScrollBar
                     x:Name="HorizontalScrollBar"
                     Grid.Column="0"
                     Grid.Row="1"
                     Orientation="Horizontal"
                     Cursor="Arrow"
                     Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}"
                     ViewportSize="{TemplateBinding ViewportWidth}"
                     Minimum="0"
                     Maximum="{TemplateBinding ScrollableWidth}"
                     Value="{TemplateBinding HorizontalOffset}"
                     Height="18"/>
               </Grid>
           </ControlTemplate>
       </Setter.Value>
   </Setter>
</Style>

So now we need to tell our ScrollViewer to use this style.

<ScrollViewer x:Name="ScrollViewerElement"
   Style="{StaticResource ScrollViewerStyle1}"
   Padding="{TemplateBinding Padding}">
   <ItemsPresenter />
</ScrollViewer>

And this is what it looks like:

image8

Kind of disappointing, huh? That's because we haven't styled the scrollbars themselves yet. Now we need to take a look at the default scrollbar style. Now these really are intimidating. They contain hundreds of lines of XAML with plenty of VisualStates, Storyboards and gradients. Even more confusingly they contain templates within templates.

We will progress by looking at each of these sub-templates one by one. First up is HorizontalIncrementTemplate, which is the right-arrow at the end of the horizontal scrollbar. Here's a simplified version of the default implementation:

<ControlTemplate x:Key="HorizontalIncrementTemplate" TargetType="RepeatButton">
   <Grid x:Name="Root" Background="#00000000">
       <vsm:VisualStateManager.VisualStateGroups>
           <vsm:VisualStateGroup x:Name="CommonStates">
               <vsm:VisualStateGroup.Transitions>
                   <vsm:VisualTransition To="MouseOver" Duration="0:0:0.2" />
               </vsm:VisualStateGroup.Transitions>
               <vsm:VisualState x:Name="Normal" />
               <vsm:VisualState x:Name="MouseOver">
                   <Storyboard>
                       <ColorAnimation Storyboard.TargetName="ButtonColor" Storyboard.TargetProperty="Color" To="#FF557E9A" Duration="0" />
                   </Storyboard>
               </vsm:VisualState>
               <vsm:VisualState x:Name="Disabled">
                   <Storyboard>
                       <DoubleAnimation Storyboard.TargetName="ButtonVisual" Storyboard.TargetProperty="Opacity" To=".6" Duration="0" />
                   </Storyboard>
               </vsm:VisualState>
           </vsm:VisualStateGroup>                                           
       </vsm:VisualStateManager.VisualStateGroups>
       <Grid.ColumnDefinitions>
           <ColumnDefinition Width="35*"/>
           <ColumnDefinition Width="30*"/>
           <ColumnDefinition Width="35*"/>
       </Grid.ColumnDefinitions>
       <Grid.RowDefinitions>
           <RowDefinition Height="25*"/>
           <RowDefinition Height="50*"/>
           <RowDefinition Height="25*"/>
       </Grid.RowDefinitions>
       <Path x:Name="ButtonVisual" Grid.Column="1" Grid.Row="1" Stretch="Fill" Data="F1 M 511.047,352.682L 511.047,342.252L 517.145,347.467L 511.047,352.682 Z ">
           <Path.Fill>
               <SolidColorBrush x:Name="ButtonColor" Color="#FF313131" />
           </Path.Fill>
       </Path>
   </Grid>
</ControlTemplate>

Although this looks like a lot of code, all that is happening is simply a triangle is being drawn. The grid simply serves to give an appropriate margin around the triangle. The animations change the colour for mouse-over. I have removed the focus rectangle as I don't need it for my purposes. The actual background to the arrow is drawn by another part of the template. So for now I will leave these as they are and to move onto the "Thumb" components.

I have simplified the thumb component to be a rounded rectangle that changes colour as you hover over it. I also played with the margins to make it a little thinner. Here is my modified VerticalThumbTemplate:

<ControlTemplate x:Key="VerticalThumbTemplate" TargetType="Thumb">
   <Grid>
       <vsm:VisualStateManager.VisualStateGroups>
           <vsm:VisualStateGroup x:Name="CommonStates">
               <vsm:VisualStateGroup.Transitions>
                   <vsm:VisualTransition To="MouseOver" Duration="0:0:0.1" />
               </vsm:VisualStateGroup.Transitions>
               <vsm:VisualState x:Name="Normal" />
               <vsm:VisualState x:Name="MouseOver">
                   <Storyboard>
                       <ColorAnimation Storyboard.TargetName="ThumbForeground"
                                       Storyboard.TargetProperty="Color"
                                       To="{StaticResource ThumbHoverColor}" Duration="0" />
                   </Storyboard>
               </vsm:VisualState>
               <vsm:VisualState x:Name="Disabled">
                   <Storyboard>
                       <DoubleAnimation Storyboard.TargetName="ThumbVisual"
                                        Storyboard.TargetProperty="Opacity"
                                        To=".6" Duration="0" />
                   </Storyboard>
               </vsm:VisualState>
           </vsm:VisualStateGroup>
       </vsm:VisualStateManager.VisualStateGroups>

       <Grid x:Name="ThumbVisual">
           <Rectangle x:Name="Background"
               Margin="4.5,.5,4.5,.5"
               RadiusX="5" RadiusY="5" >
               <Rectangle.Fill>
                   <SolidColorBrush x:Name="ThumbForeground"
                   Color="{StaticResource ThumbForegroundColor}" />
                </Rectangle.Fill>
           </Rectangle>
       </Grid>
   </Grid>
</ControlTemplate>

With a similar change to the HorizontalThumbTemplate, our scrollbars are now finally beginning to change in appearance (n.b. To see the changes we have also had to modify our ScrollViewer style so that the two scrollbars it creates use the new ScrollBar style). Here's a screenshot showing the mouse hovering over the vertical thumb:

image31

Finally we are ready to update the remaining parts of the ScrollBar template - HorizontalRoot and VerticalRoot. Both are made up of a grid containing four repeat buttons and a thumb. Two of the repeat buttons are for the increment icons, while the other two are the invisible parts either side of the thumb that you can click for a large change.

Again, the change is simply to get rid of a load of unnecessary stuff. In our case we are simply putting a thin rounded rectangle behind the thumb and invisible repeat buttons, with no background behind the small increment buttons. Here's the new HorizontalRoot template:

<!-- Horizontal Template -->
<Grid x:Name="HorizontalRoot">
   <Grid.ColumnDefinitions>
       <ColumnDefinition Width="Auto" />
       <ColumnDefinition Width="Auto" />
       <ColumnDefinition Width="Auto" />
       <ColumnDefinition Width="*" />
       <ColumnDefinition Width="Auto" />
   </Grid.ColumnDefinitions>

   <Grid.RowDefinitions>
       <RowDefinition />
       <RowDefinition />
   </Grid.RowDefinitions>

   <!-- Track Layer -->
   <Rectangle Margin="1,6,1,6"
     Grid.RowSpan="2" Grid.Column="1"        
     Grid.ColumnSpan="3" Fill="#FF606060"
     RadiusX="3" RadiusY="3" />

   <!-- Repeat Buttons + Thumb -->
   <RepeatButton x:Name="HorizontalSmallDecrease" Grid.Column="0" Grid.RowSpan="2" Width="16" IsTabStop="False" Interval="50" Template="{StaticResource HorizontalDecrementTemplate}" />
   <RepeatButton x:Name="HorizontalLargeDecrease" Grid.Column="1" Grid.RowSpan="2" Width="0" Template="{StaticResource RepeatButtonTemplate}" Interval="50" IsTabStop="False" />
   <Thumb x:Name="HorizontalThumb" MinWidth="10" Width="20" Grid.Column="2" Grid.RowSpan="2" Template="{StaticResource HorizontalThumbTemplate}" />
   <RepeatButton x:Name="HorizontalLargeIncrease" Grid.Column="3" Grid.RowSpan="2" Template="{StaticResource RepeatButtonTemplate}" Interval="50" IsTabStop="False" />
   <RepeatButton x:Name="HorizontalSmallIncrease" Grid.Column="4" Grid.RowSpan="2" Width="16" IsTabStop="False" Interval="50" Template="{StaticResource HorizontalIncrementTemplate}" />
</Grid>

We make a similar change for the VerticalRoot and here's what it looks like:

image6

The bar alongside the vertical scrollbar is actually a very stretched horizontal scrollbar. For some reason, while it successfully uncollapses the VerticalRoot, it does not collapse the HorizontalRoot when you create a vertical scrollbar. After much frustration I discovered that this is a known bug in the current Silverlight beta and sadly it has not been fixed in Beta 2.

So finally we have completely customised scrollbars for our ListBox. Please excuse my hideous choice of colours. I am not a designer! I hope to add one further post to add the remaining two features to make our ListBox complete:

  • Selected Item Rendering
  • Mouse Over Rendering

Continue to Part 3...

Thursday, 19 June 2008

Styling a ListBox With Silverlight 2 Beta 2 (Part 1)

This post is an updated version of an earlier series I wrote on how to style a ListBox with Silverlight. I hope to update all three parts over the coming days. This tutorial is not about how to use Expression Blend, as there are plenty of other blogs that will explain that. This is for those who like to go right to the XAML.

One of the challenges of styling a control like the ListBox in Silverlight is the sheer number of subcomponents it uses. A ListBox has its own template which includes a ScrollViewer and an ItemPresenter. The ScrollViewer contains Scrollbars which contain RepeatButtons, Thumbs etc.

My original idea was to make copies of the default styles and slowly change them to look how I wanted, but I soon realised that the sheer quantity of XAML would get very confusing. So I decided to take the opposite approach. Start with a very basic template and slowly add features until it looks right. So here is the most basic of all ListBox styles which contains just a simple template:

<Style x:Key="ListBoxStyle1" TargetType="ListBox">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ListBox">
                <Grid x:Name="Root">
                    <ItemsPresenter />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

This simply presents the items, with no outline of any sort displayed. To test our style, let's add some items to a ListBox (notice that with Silverlight 2 Beta 2 I need to put TextBlocks inside my ListBoxItem instead of just text that worked fine in Beta 1)

<ListBox Margin="5" Width="160" Height="160"
 Style="{StaticResource ListBoxStyle1}">
    <ListBoxItem><TextBlock Text="Hello"/></ListBoxItem>
    <ListBoxItem><TextBlock Text="World"/></ListBoxItem>
    <ListBoxItem><TextBlock Text="Item 3"/></ListBoxItem>
    <ListBoxItem><TextBlock Text="Item 4 with a really long name"/></ListBoxItem>
    <ListBoxItem><TextBlock Text="Item 5"/></ListBoxItem>
    <ListBoxItem><TextBlock Text="Item 6"/></ListBoxItem>
    <ListBoxItem><TextBlock Text="Item 7"/></ListBoxItem>
    <ListBoxItem><TextBlock Text="Item 8"/></ListBoxItem>
    <ListBoxItem><TextBlock Text="Item 9 out of bounds"/></ListBoxItem>
    <ListBoxItem><TextBlock Text="Item 10 out of bounds"/></ListBoxItem>
</ListBox>

This is what it looks like so far:

ListBox Style Step 1

Next step is the border for our ListBox. I want all the ListBox items to be drawn on top of a filled rounded rectangle. To do this, I have added a Border control. I have given it some padding so we can actually see it, because the ListBoxItem template is currently drawing white rectangles over the top of it.

<Grid x:Name="Root">
  <Border Padding="5" Background="#E6BB8A" CornerRadius="5">
    <ItemsPresenter />
  </Border>
</Grid>

This is what it looks like now:

Listbox Style Step 2

So before we go doing anything further to the ListBox template itself (like adding scrollbars), let's sort out the item templates.

For this we need to create a new style - ListBoxItemStyle1. Here is a minimal ListBoxItem style:

<Style x:Key="ListBoxItemStyle1" TargetType="ListBoxItem">
    <Setter Property="Foreground" Value="#FF000000" />    
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ListBoxItem">
                <Grid x:Name="Root">
                    <ContentPresenter
                        Content="{TemplateBinding Content}"
                        Foreground="{TemplateBinding Foreground}"
                     />                    
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

As you can see, it is a little more involved than the basic ListBox template. We needed to have the Foreground property set to a sensible default value (Black) for anything to appear. And we have simply used one ContentPresenter control to show the contents of each ListBox item.

(n.b. Remember to define the ListBoxItemStyle before your ListBox style. Expression Blend will be OK with this, but when you come to run it, Silverlight will fail with one of its characteristically unhelpful errors.)

We can tell our ListBox to use it by modifying our ListBox Style as follows:

<Style x:Key="ListBoxStyle1" TargetType="ListBox">
    <Setter Property="ItemContainerStyle" Value="{StaticResource ListBoxItemStyle1}" />
    <Setter Property="Template">
        ...

Now we have got rid of those white backgrounds:

ListBox Style Step 3

Finally we will make the item template just a little more interesting. I've added a border to the item presenter, and modified some margins and colours:

<Border CornerRadius="5" Background="#51615B" Margin="1">
<ContentPresenter
    Margin="1"
    Content="{TemplateBinding Content}"
    Foreground="{TemplateBinding Foreground}"
 />                    
 </Border>

This leaves us with something looking like this:

ListBox Style Step 4

So that is at least a reasonable start. Our ListBox is missing at least three crucial features though, which I will tackle in a future blog-post:

  • Scrollbars
  • Selected Item Rendering
  • Mouse Over Rendering

Continue to Part 2...

Tuesday, 10 June 2008

Font Embedding in Silverlight 2 beta 2

I added a font to my SilverNibbles game this weekend as part of converting to beta 2. You can see it in action here.

The way to do this is relatively straightforward:

1. Add your font to the project. The build action should be Resource. You do not need to copy to the output directory. Visual Studio will put it into your DLL file at compile time. (n.b. If you choose Content instead, it will go into your XAP file which also works, but apparently loading fonts from the XAP will not be supported after beta 2 so this method is not recommended)

2. Now whenever you need to use the font, simply use the syntax FontFamily="Font Name.ttf#FontName".

Font Embedding in Silverlight

And that is all there is to it. 

Monday, 9 June 2008

Basic Button Templating in XAML in Silverlight 2 Beta 2

There has been lots of buzz about the new control templating mechanism introduced with Silverlight 2 beta 2. It looks like the main driver behind this is allowing you to template controls using Expression Blend. Scott Guthrie covers this in depth in this post.

However, I always like to know exactly what is going on with my XAML, and I needed to style a button for my SilverNibbles game, so I decided to see how hard it would be.

As usual, the best place to start is by looking in MSDN at the existing templates for the controls. Although these are often bewilderingly long chunks of XAML, most of the time, you can throw large portions of it away.

For example, my button only needs two visual states - normal and mouse over. I am just going to darken the background slightly when the mouse is over the button:

silverlight-basic-button-templating

I decided to put my style in the App.xaml file in the <Application.Resources> section. To start with, I just customised the font. Notice I have also added in a vsm namespace for use with the Visual State Manager later.

<Style 
    xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"
    TargetType="Button"
    x:Key="NewGameButtonStyle">
    <Setter Property="FontFamily" Value="teen bold.ttf#Teen" />
    <Setter Property="FontSize" Value="18" />
</Style>

The next task is to put a Template into the Style and design the basic layout of our button. Although this looks like a lot of code, all it is is a Grid which contains a Border which contains a ContentPresenter. We could actually leave off most the ContentPresenter's properties, as our button does not need that level of customisation (we are only using it in one place). The Border brushes are set using named SolidColorBrush objects so we can animate them later if we wish.

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="Button">
            <Grid>
                <Border BorderThickness="2" 
                        CornerRadius="4"
                        Padding="3"                                    
                        >
                    <Border.Background>
                        <SolidColorBrush x:Name="ButtonBackgroundBrush" Color="AliceBlue"/>
                    </Border.Background>
                    <Border.BorderBrush>
                        <SolidColorBrush x:Name="ButtonBorderBrush" Color="Black"/>
                    </Border.BorderBrush>
                    <ContentPresenter
                      Content="{TemplateBinding Content}"
                      ContentTemplate="{TemplateBinding ContentTemplate}"
                      HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                      Padding="{TemplateBinding Padding}"
                      TextAlignment="{TemplateBinding TextAlignment}"
                      TextDecorations="{TemplateBinding TextDecorations}"
                      TextWrapping="{TemplateBinding TextWrapping}"
                      VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
                      Margin="4,2" />
                </Border>
            </Grid>
        </ControlTemplate>
    </Setter.Value>
</Setter>

Now the final task is to use the new VisualStateManager to tell our control what we want to happen on MouseOver. We will define one VisualStateGroup - the "CommonStates" group, which will contain two VisualStates and two VisualTransitions. The first VisualState is the Normal state, for which we don't need to do anything. The second VisualState is the MouseOver state, which contains a StoryBoard that animates the colour of the button's background. Notice that the duration is zero. This is a little confusing, but the duration will actually be set by the VisualTransitions. The VisualTransitions simply let us set the length of time over which we will change to the VisualStates. Here's our VisualStateGroups, which we have put inside the Grid XAML element:

<vsm:VisualStateManager.VisualStateGroups>
    <vsm:VisualStateGroup x:Name="CommonStates">

        <vsm:VisualStateGroup.Transitions>
            <vsm:VisualTransition To="MouseOver" Duration="0:0:0.2" />
            <vsm:VisualTransition To="Normal" Duration="0:0:0.2" />
        </vsm:VisualStateGroup.Transitions>

        <vsm:VisualState x:Name="Normal" />
        <vsm:VisualState x:Name="MouseOver">
            <Storyboard>
                <ColorAnimation 
                Storyboard.TargetName="ButtonBackgroundBrush"
                Storyboard.TargetProperty="Color"
                To="#C0C0C0"
                Duration="0" />
            </Storyboard>
        </vsm:VisualState>
    </vsm:VisualStateGroup>
</vsm:VisualStateManager.VisualStateGroups>

So templating controls is still perfectly possible in XAML, if you don't mind writing lots of it, but I guess that the intention now is for it all to be done in Expression Blend.

I'm hoping to find time over the next few weeks to update my series on styling a listbox to work with the new beta 2 templating model.

Wednesday, 28 May 2008

Combining Paths in XAML for Silverlight

Play button in XAML

I have been attempting to make some nice looking buttons to use with my Silverlight Audio Player, and came up with a basic design in XAML, borrowing some colour ideas from iTweek's icons on deviantart. The XAML for the basic play button with drop shadow is:

<Ellipse Canvas.Left="53" Canvas.Top="76" Width="26" Height="8" Fill="#40000000" />
<Ellipse Canvas.Left="50" Canvas.Top="50" Stroke="#396C15" Width="32" Height="32">  
  <Ellipse.Fill>
    <LinearGradientBrush EndPoint="0,1">
      <GradientStop Color="#1070B434" Offset="0.0" />
      <GradientStop Color="#70B434" Offset="0.5" />
      <GradientStop Color="#FFAFD855" Offset="1.0" />
    </LinearGradientBrush>      
  </Ellipse.Fill>
</Ellipse>
<Path Canvas.Left="50" Fill="#FFFFFF" Stroke="#396C15" Data="M 13,58 l 10,8 l -10,8 Z" StrokeLineJoin="Round" />

Things got a bit more interesting when I tried to make a fast-forward icon by overlapping two triangles. Simply drawing two triangles over the top of each other does not give the desired result:

<Path Canvas.Left="80" Fill="#FFC0C0" Stroke="#396C15" Data="M 13,58 l 10,8 l -10,8 Z "
  StrokeLineJoin="Round"  />
<Path Canvas.Left="80" Fill="#FFC0C0" Stroke="#396C15" Data="M 18,58 l 10,8 l -10,8 Z " 
  StrokeLineJoin="Round"  />

XAML Overlapping Triangles

The Path Data property allows you to specify more than one closed shape, but this results in the strokes of both triangles being visible rather than combining to form one outline. This happens whether you use the Path syntax or create a GeometryGroup and add PathGeometrys. Rather annoyingly PathGeometry does not have a Data Property, which makes for some cumbersome XAML:

<Path Canvas.Left="105" Fill="#FFC0FF" Stroke="#396C15" Data="F 1 M 13,58 l 10,8 l -10,8 Z M 18,58 l 10,8 l -10,8 Z"
  StrokeLineJoin="Round"  />

<Path Canvas.Left="130" Fill="#FFFFC0" Stroke="#396C15" Data="M 13,58 l 10,8 l -10,8 Z M 18,58 l 10,8 l -10,8 Z" 
  StrokeLineJoin="Round"  />

<Path Canvas.Left="155" Fill="#C0FFC0" Stroke="#396C15" StrokeLineJoin="Round">
  <Path.Data>
    <GeometryGroup FillRule="NonZero">
        <PathGeometry>
          <PathFigure StartPoint="13,58" IsClosed="True">
            <LineSegment Point="23,66"  />
            <LineSegment Point="13,74"  />
          </PathFigure>
        </PathGeometry>
        <PathGeometry>
        <PathFigure StartPoint="18,58" IsClosed="True" >
            <LineSegment Point="28,66"  />
            <LineSegment Point="18,74"  />
          </PathFigure>
        </PathGeometry>
    </GeometryGroup>                  
  </Path.Data>
</Path>

XAML Path Geometries

This is still not the effect I want, irrespective of the FillRule used. The solution in WPF is to use a CombinedGeometry. This allows two PathGeometrys to be specified that can be combined as a union to create one shape. Again we have very verbose XAML because we can't use the Path mini language:

<Path Canvas.Left="180" Fill="#C0C0FF" Stroke="#396C15" StrokeLineJoin="Round">
  <Path.Data>
    <CombinedGeometry GeometryCombineMode="Union">
      <CombinedGeometry.Geometry1>
        <PathGeometry>
          <PathFigure StartPoint="13,58" IsClosed="True">
            <LineSegment Point="23,66"  />
            <LineSegment Point="13,74"  />
          </PathFigure>
        </PathGeometry>
      </CombinedGeometry.Geometry1>
      <CombinedGeometry.Geometry2>
        <PathGeometry>
          <PathFigure StartPoint="18,58" IsClosed="True" >
            <LineSegment Point="28,66"  />
            <LineSegment Point="18,74"  />
          </PathFigure>
        </PathGeometry>
      </CombinedGeometry.Geometry2>
    </CombinedGeometry>
  </Path.Data>
</Path>

This produces the shape I wanted:

XAML Combined Geometry

But now we run into another problem. The Silverlight 2 beta does not support CombinedGeometry, and I have no idea if this is going to be supported as part of the full release of Silverlight 2.

So how can we get this in Silverlight? At the moment I know of only two solutions:

1. Do the maths yourself. For two triangles as in my example, this wouldn't be too hard, but it would be a real pain if your combined shape involved any curves or ellipses.

2. Get Expression Blend to do it for you. Draw the two shapes, select them, then select Object | Combine | Unite. This will create a single path you can use in a Silverlight application. It doesn't leave the XAML quite how I would like it (adding margins and using absolute coordinates in the path, rather than relative).

<Path Height="17" 
  HorizontalAlignment="Left" 
  Margin="138.5,91.5,0,0" 
  VerticalAlignment="Top" 
  Width="16" Fill="#C0C0FF" Stretch="Fill" 
  Stroke="DarkGreen" 
  StrokeLineJoin="Round"
  Data="M0.5,0.5 L5.5,4.5 L5.5,0.5 L15.5,8.5 L5.5,16.5 L5.5,12.5 L0.5,16.5 L0.5,0.5 z"/>

Expression Blend Combined Shape