Unable to set TestContext property for my class (.NET Compact Framework)

Suppose you’re using Visual Studio 2008 and you’ve just found out that Microsoft added unit test support for the Compact Framework on devices and emulators. Neat-o!

So you add one to your project thinking, this’ll be fantastic.

Then it doesn’t work.

You get the following cryptic error:

Unable to set TestContext property for the class {class}. Error:  System.ArgumentException: Object of type 'Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapterContext' cannot be converted to type 'Microsoft.VisualStudio.TestTools.UnitTesting.TestContext'

“So,” you think, “I obviously did something wrong, but it’s not apparent to me what I did. I will check the Google.”

But Google only shows you what to do for the full framework.The answer for the full framework is to delete your reference to Microsoft.VisualStudio.QualityTools.UnitTestFramework, then search for it again in the Add Reference dialog. Microsoft forgot to update all the project templates for VS08, so all of the esoteric projects point to the assemblies for VS 2005. Quality tool, my ass. The full framework instructions don’t make any sense for your awesome Compact Framework assembly. Uh oh, now what are you going to do?

Maybe it’s your project that’s screwed up. So you start a new one to see if it works. It doesn’t, but you get a different error: References root node unavailable. You might as well search the google for that one and then you get this forum post that repeats the solution over and over:

Restart the IDE.

You figure it can’t hurt, so you try it.

And it works.

You can now use unit tests for .NET CF projects, but you’re no longer smiling about it.

The Missing .NET #5: Tracepoints

The .NET framework is huge, but not so huge that it does everything for everyone; there are things that they in Redmond miss or don’t do for whatever reason but is still generally applicable to many developers. So, dear reader, I present to you a series of posts on stuff I find missing in .NET, typically where even the Google fails to find the answer. It could be a useful class, a technique, a good practice or documentation that should be in the framework but isn’t or isn’t widely publicized. Click here for a complete list of Missing .NET entries.


Lately, I’ve been debugging windowing code often. Windowing code is stuff like window sizing, resizing, painting, etc.; code that has something to do with drawing the window. Debugging that code used to be fairly arduous because anytime you stepped into your method, looked around, then started execution again, the windowing code would need to be re-run because you had Visual Studio focused and not your app; since you have a breakpoint in the windowing code, Visual Studio would break into your method which you probably didn’t want this time because you were already there, so you hit F5 again to continue execution and start the cycle over.

Do that for 10 minutes and you soon wise up; you strew print statements all over the place to get at the data you want to debug, figure out what you’re doing wrong, stop, fix, run and repeat. Once you’ve fixed your bug, then you delete the print statements if you’re not totally pressed for time, in which case, all kinds of debugging code just hangs around there forever and ever for everybody to ignore until someone comes around to delete it. Then, and only then, another drawing bug comes in starting the whole process all over again. Wouldn’t it be awesome if there was a way to break into a method to see the data without breaking in and without all those print statements? Fortunately, Microsoft thought that this scenario was painful enough that they put this feature in. It’s called Tracepoints; it’s been around since Visual Studio 2005.

We’re doing something a little different in this Missing .NET edition: highlighting something that is in the framework (well, peripheral to it, technically, but isn’t VS synonymous to .NET in everyone’s mind?), but that most people probably don’t know about, but should because it’s so useful.

I find this feature useful for the above scenario but also for bug source hunting. It’s a great way to find the source of an issue without breaking into the code and stepping into everything.

To setup a tracepoint, there are, of course, many ways to do it. My favourite is to create a breakpoint by clicking in the margin on the right of the code window, then right-clicking and choosing When Hit…

Setting up a tracepoint: right-click on a breakpoint and select When Hit...

You’re presented with the following dialog:

tracepointdialog

The dialog pretty much says it all.

I always choose Print a message and delete the default. The $FUNCTION keyword prints the whole method name including namespace and parameter types which is a little too talky for me. I write out the method name, typically, and then any variables I’m interested in.

For example, the last bug fix was in a SizeChanged event handler that I traced with the following: "mainMenu_SizeChanged: {Size}, {RestoreBounds.Size}"

This prints out the Size and RestoreBounds.Size properties of the Window class in which I’m tracing.

For more on breakpoints and tracepoints, check out the MSDN documentation here.

Got any tips for using the debugger?

BabySmash IV: ItemsControl and Data-bound UIs

For background on what BabySmash is, read Scott Hanselman’s post here.

This post was inspired by Ian Griffiths’s logged issue in the BabySmash issue tracker, titled "Application Logic Does Not Belong in Code Behind." My gut reaction was that that was overkill for such a simple application. BabySmash has almost no logic to it; it basically take what’s pressed and shows it on screen. I was still going to write a post about the technique because of its relevance to any app that displays data; I think databound list controls should be the most common WPF idiom, it’s so important. But, something still rankled about going so far for such a simple concept. So, I went through with the refactoring, and I gotta tell you: Ian was absolutely right.

You should read Ian’s description one of the problems with the BabySmash code. He also describes a solution, but if you aren’t familiar with the ItemsControl, most of it will go right over your head (hopefully not after this post though). I think it’s best if we describe BabySmash in a way that will help us move to Ian’s solution. Databinding in WPF, especially list-bound data, is where WPF diverges from the UI technologies that inspired it. It’s not immediately obvious with BabySmash’s raison d’etre that we can make it data-bound; I’ve found, however, that once you know about WPF’s databinding, you want to model your domain classes to take advantage of it. That’s how I approached changing BabySmash this time. Mike Hillberg has a good post on writing the domain model with WPF.

One more thing before I begin. Modelling any domain problem is subject to opinion. Software design is a matter of trade offs. You may prioritize different parts of the problem than I. Talking about ItemsControl requires a data model. I’ll talk about the model I chose. Hopefully, if you disagree with my object model, the technique of using an ItemsControl I show here can still applied to your model. I’m also not going to dwell too long on all the whys of my object model, although that’s an interesting topic as well. I welcome feedback or those why questions in the comments.

Where’s the data?

Allow me to distill BabySmash down to requirements language:

When a user presses a key in BabySmash, then, depending on the key pressed, a shape, letter or number will be pressed:

  • if the key is a letter key (A through Z), then that letter is displayed on screen in a random position with a random colour;
  • if the key is a number, the behaviour is the same as for letters; and
  • if the key is anything else, a shape is chosen at random and displayed on screen in a random position with a random colour

The shapes drawn are currently square, circle, triangle and star.

Depending on a user setting, as each key is pressed, either laughter or speech is heard. If speech is chosen, then the shape or letter put on screen is announced.

How’s that?

I’ve written it down that way so we can "see where the classes are." Good domain design is all about getting the class model right. Looking at the above description, I can see a few good candidate classes for the essential BabySmash: shape (including square, circle, triangle and star), letter, number, position, colour and sound.

We can break these down further into two categories: display and data. The colour, sound and position have to do with display. The "data" is what shape to draw: the letter, number, or shape dictated by the key press. I’d say the essence of BabySmash is the data category. Below is the class definition that I came up with for that concept:

public abstract class Figure
{
   private UIElement shape;
   private readonly string name;
   
   protected Figure(Brush fill, string name)
   {
      this.name = name;
   }

   public UIElement Shape
   {
      get { return shape; }
      protected set { shape = value; }
   }

   public string Name
   {
      get { return name; }
   }
}

My abstract Figure class has a Shape, typed to UIElement, associated with it and a name. In the constructor, I pass the Brush that will fill the shape. This allows me to create arbitrarily complex shapes to display; here are a couple Figure classes that inherit from Figure:

public class LetterFigure : Figure
{
  public LetterFigure(Brush fill, string name)
     : base(fill, name)
  {
     string nameToDisplay;
     if (Properties.Settings.Default.ForceUppercase)
     {
        nameToDisplay = name;
     }
     else
     {
        if (Utils.GetRandomBoolean())
           nameToDisplay = name;
        else
           nameToDisplay = name.ToLowerInvariant();
     }
     Shape = Utils.DrawCharacter(400, nameToDisplay, fill);
  }
}

public class SquareFigure : Figure
{
  public SquareFigure(Brush fill)
     : base(fill, "square")
  {
     Shape = new Rectangle()
     {
        Fill = fill,
        Height = 380,
        Width = 380,
        StrokeThickness = 5,
        Stroke = Brushes.Black,
     };
  }
}

Basically, I took the code from Window1.xaml.cs in the BabySmash solution that creates the shapes and broke it out into classes. There are also CircleFigure, StarFigure and TriangleFigure that are similar to SquareFigure above. I probably could move the Utils.DrawCharacter() code into the LetterFigure constructor as a further refactoring.

We also need a way to create Figures based on input from the user. That class is below:

public class FigureGenerator 
{
  private int clearAfter;
  private readonly ObservableCollection<Figure> figures = new ObservableCollection<Figure>();
  
  public int ClearAfter
  {
     get { return clearAfter; }
     set { clearAfter = value; }
  }

  public ObservableCollection<Figure> Figures
  {
     get { return figures; }
  }

  public void Generate(string letter)
  {
     if (figures.Count == clearAfter)
        figures.Clear();

     figures.Add(GenerateFigure(letter));
  }

  private Figure GenerateFigure(string letter)
  {
     //TODO: Should this be in XAML? Would that make it better?
     Brush fill = Utils.GetRandomColoredBrush();
     if (letter.Length == 1 && Char.IsLetterOrDigit(letter[0]))
     {
        return new LetterFigure(fill, letter);
     }
     else
     {
        int shape = Utils.RandomBetweenTwoNumbers(0, 3);
        //TODO: Should I change the height, width and stroke to be relative to the screen size?
        //TODO: I think I need a shapefactory?
        switch (shape)
        {
           case 0:
              return new SquareFigure(fill);
           case 1:
              return new CircleFigure(fill);
           case 2:
              return new TriangleFigure(fill);
           case 3:
              return new StarFigure(fill);
        }
     }
     return null;
  }
}

Again, you can see by the TODOs, I just took Scott’s code and moved it around. The FigureGenerator class holds onto the Figures collection that will be used in the UI as the data source. The Figures collection is typed to ObservableCollection<Figure>. This is one of those magic classes offered by WPF that can track changes, so adding a figure to the collection adds an element on screen. FigureGenerator also takes input from the Window class through the Generate() method.

Consuming the Data

OK, we’ve got our data model. Now we want to display it. I’m taking Ian’s recommendations, namely using an ItemsControl,. I’ll break this down into steps.

The first thing is to add the ItemsControl to the Window. We’ll do that in XAML. At the same time I’ll declare my FigureGenerator that will generate the figures. Here’s the XAML first:

<Window>
    <Window.Resources>
        <local:FigureGenerator x:Key="figureGenerator"/>
    </Window.Resources>
    <Grid Name="grid">
        <ItemsControl Name="figures" 
                      ItemsSource="{Binding Source={StaticResource figureGenerator},Path=Figures}">            
        </ItemsControl>
    </Grid>
</Window>

I spoke about StaticResources before. Essentially, what I’m doing here is adding a FigureGenerator instance to the Window’s resources. Then, I’m binding the ItemsControl to the Figures property on the FigureGenerator. There is one more thing I have to do in the code-behind. When a key is pressed, I have to tell the FigureGenerator instance about it. Here are the relevant bits from the code behind:

private FigureGenerator figureGenerator;
public Window1()
{
    objSpeech = new SpVoice();
    InitializeComponent();
   figureGenerator = (FigureGenerator) this.Resources["figureGenerator"];
   figureGenerator.ClearAfter = Properties.Settings.Default.ClearAfter;   
}

private void Window_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
    PlayLaughter();

    string s = e.Key.ToString();
    if (s.Length == 2 && s[0] == 'D') s = s[1].ToString(); //HACK: WTF? Numbers start with a "D?"
    figureGenerator.Generate(s);
}

You can run BabySmash now, but what you’ll see isn’t that entertaining:

BabySmash with an unstyled ItemsControl

What’s happening here? We’re using an ItemsControl with the default templates, which just shows each item in the collection using it’s ToString() method; the items are contained in a StackPanel. In Figure’s case, since we didn’t override it, uses Object.ToString(), which prints the type name. Let’s fix that.

The ItemsControl is an important control. It’s the basis for all of the collection controls: TreeView, ListView, ListBox, TabControl, even ComboBox and Menu. All those classes use the behaviour inherited from ItemsControl to display themselves in obviously different ways; i.e. they’re all special cases of the basic ItemsControl (to a first approximation anyway, I’m glossing over some important details). We’re going to show how to customize the look of an ItemsControl in the same way that the above controls do it.

In the XAML above, we told the ItemsControl where our data is, but we haven’t told the ItemsControl how to display it. We do that with Templates. Every control in WPF has a Template that dictates the look of the control. WPF introduces the concept of a lookless control; a control whose appearance is independent from behaviour. The best example of the lookless control is the button. What shape the button takes is independent of what makes a button a button, namely that you can click it. It’s roughly analogous to how CSS affects elements’ appearance in HTML. Typically, a control’s appearance can be modified by replacing it’s ControlTemplate via the Template property. ItemsControl is a little bit different though.

With ItemsControls, we can manipulate independent parts of ItemsControls with different templates. The template you’ll use most often in your apps is the ItemTemplate. The ItemTemplate property is typed to DataTemplate, which as the name suggests can be used to template your data, which can be of any type. This is a very powerful concept. It allows us to display any old type with the same ItemsControl, something pretty much impossible with Windows Forms or Win32 or anything else. We get infinite custom controls.

Let’s make an ItemTemplate for BabySmash. Most of it is already done for us. Scott made the basic shapes, I just moved them into different classes. The thing we want to display can be accessed by the Shape property on the Figure class. Now we want to tell WPF to display that. We do that with the magic ContentPresenter. The ContentPresenter presents whatever you give it the best way it can. Pass it a Button, it’ll display that button. Pass it a string, it’ll print a TextBlock with the string as Text; pass it an object, it’ll print a TextBlock with the string from its ToString() as Text. That’s right, we’ve been using a ContentPresenter all along. We have the shape we just have to point to it.

<ItemsControl Name="figures" 
              ItemsSource="{Binding Source={StaticResource figureGenerator},Path=Figures}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <ContentPresenter Content="{Binding Path=Shape}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Let’s run it again:

items2

Looking better.

Now we want those letters to show up all over the screen. To do that requires two changes. The first, we have to change the underlying Panel that our ItemsControl uses to layout its Items. I mentioned above that ItemsControl uses a StackPanel by default. We’re concerned with position, therefore we only have one choice: Canvas. We do this by setting the ItemsPanel property to an ItemsPanelTemplate object that contains a Canvas:

<ItemsControl Name="figures" ItemsSource="{Binding Source={StaticResource figureGenerator},Path=Figures}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <ContentPresenter Content="{Binding Path=Shape}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

If you ran it now, you wouldn’t see anything different. That’s because we’re not setting the Canvas.Left and Canvas.Top attached properties on the shapes yet. You may think we should do that on the ItemTemplate above; I know I did when I was figuring this out a few weeks ago (I tried this same trick of using an ItemsControl for a line graph, a subject for a future post). Well, you’d be wrong.

There’s a third aspect of the ItemsControl: the item container. The item container is responsible for selection management of that item in the collection. There is no specific class hierarchy for it, but if you look around in Reflector, you’ll see that each ItemsControl child (like ListBox, ComboBox, etc) has an override for the GetContainerItemOverride() and returns its item container class (whose name follows from the control with which its associated: ListBoxItem for ListBox and so on). If you inspect the Visual Tree, you’ll see that the actual items in the ItemsControl are the associated item container. It’s this container that we want to manipulate to place the item. We do that with the ItemContainerStyle property on the ItemsControl. Incidently, ItemsControl uses FrameworkElement as it’s container.

<ItemsControl Name="figures" 
              ItemsSource="{Binding Source={StaticResource figureGenerator},Path=Figures}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <ContentPresenter Content="{Binding Path=Shape}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style>
            <Setter Property="Canvas.Left" 
                    Value="{Binding RelativeSource={RelativeSource FindAncestor, 
                            AncestorType={x:Type local:Window1}},Path=ShapeLeft}"/>
            <Setter Property="Canvas.Top" 
                    Value="{Binding RelativeSource={RelativeSource FindAncestor, 
                            AncestorType={x:Type local:Window1}},Path=ShapeTop}"/>
        </Style>
    </ItemsControl.ItemContainerStyle>
</ItemsControl>

This is the entire ItemsControl. Note there are many ways that occurred to me to create the random numbers for Top and Left. I thought the simplest would be to add two properties on the Window1 class, and then bind to them using a syntax you probably haven’t seen before. This method traverses the XAML (more technically, the visual or logical tree) directly to get to the data source. I’m telling WPF to find the first Window1 class instance in the tree, then bind to either ShapeLeft or ShapeTop properties. Those properties generate random doubles and consist of Scott’s code cut and pasted.

One more thing to add back and we’re done.

If the user chooses Speech as the option for sound, a computer voice is supposed to speak the letter or shape that was just shown. We got rid of that when I rewrote the Window_KeyUp method above. Let’s add it back.

When you set the ItemsSource property on an ItemsControl, the ItemsControl does one more indirection on you. It wraps the source in an ICollectionView. The ICollectionView monitors the collection for changes and handles currency for the ItemsControl. The ListBox, or any other ItemsControl, is completely ignorant of the currently selected item, and so is the source collection (which is typed to IEnumerable<T>). This separation allows for synchronizing multiple controls on the same collection, so that if the selection changes all controls are updated. The ICollectionView is associated with the source, not the targets. The cool thing is, we can access it directly; filtering, grouping and sorting are all accomplished with the collection view (something I use to make an autocomplete text box in WPF). So, we’ll use that to be notified of any collection additions and play the appropriate speech based on the item.

public Window1()
{
    objSpeech = new SpVoice();
    InitializeComponent();
   figureGenerator = (FigureGenerator) this.Resources["figureGenerator"];
   figureGenerator.ClearAfter = Properties.Settings.Default.ClearAfter;
   ICollectionView collectionView = CollectionViewSource.GetDefaultView(figureGenerator.Figures);
   collectionView.CollectionChanged += FiguresCollectionChanged;
}

private void FiguresCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
  if (e.Action == NotifyCollectionChangedAction.Add)
  {
     Figure f = (Figure) e.NewItems[0];
     SpeakString(f.Name);
  }
}

Hit F5. BabySmash is back in all its glory!

So was this worth it?

Before I did this, Window1.xaml.cs weighed in at about 230 lines. Now it’s a svelte 125 lines, but I added about 180 lines with that Figure stuff! I’m not even including the XAML either.

Still, I think I reduced the cognitive load of the app. By putting the display logic in XAML, I noticed that I could concentrate more on what the app was doing. Before, it was all code, so you didn’t really know where to look.

Now, we only need concern ourselves with one idea, Figure, when we’re thinking about BabySmash in general. With a little more work, we can add other shapes as the kids get older like dodecahedron; or animal shapes or pictures of family. Score one for extensibility.

We’ve also somewhat separated the appearance of the shapes from the shapes themselves. Score one for encapsulation.

We can also test the FigureGenerator and Figure classes without a UI. Score one for automated testing.

Hopefully, I’ve shown how the ItemsControl provides huge benefits for displaying your domain here. If you want to play around some more, I suggest using ListBox with a custom ItemTemplate to get a feel for how it works.

Using Commands in BabySmash

For background, you should read the first post by Scott Hanselman on his BabySmash project. I’ve already written one post on how to to do configuration better. In this post, I’ll cover another aspect of WPF that Microsoft got right: commands.

I’ve written about commands before. In that post, I was describing a way to implement Commands in Windows Forms. They are completely missing in Windows Forms, but in WPF, they got first class treatment.

Why Commands?

In my WinForms article, I didn’t really discuss what Commands were. Oh well. I’ve always told myself to proof read, but I never seem to listen.

Consider an operation like opening a text file. Suppose you were writing a notepad clone. That would be an important operation to support. Notepad has a menu with a menu item that shows the system’s OpenFileDialog, lets you pick a file and open it, display it, etc. Now suppose you wanted to do one better than Notepad and you wanted a right-click menu with a menu item that does the same thing. You’d handle the Click event for your new context menu item, and do the same thing as in your notepad clone’s main menu item. A little later in the dev cycle, you decide you’re going to have a Toolbar with a button that lets you open a file too. Then you decide that your notepad clone is so important that you’re going to have a icon in the system tray with a context menu that lets you open a file from one of the menu items. I could go on and on with, say, keyboard shortcuts and the like, but I think I’ve gone far enough.

What does your code look like now? If you were smart, you’d have one method in your Window class that would handle opening a file and call that method from all the click handlers. If you were really smart, you’d hook up all the Click events you were handling to the same method. But you probably handle each one separately and copy the code each time. That’s what I’d do when I was just starting out.

This is probably fine for a notepad clone; it’s fairly straightforward, there’s one window that doesn’t do much. If you started out with the write once/paste anywhere coding style, you could refactor to a more streamlined approach like the other two above. But consider how Visual Studio would look like if it took this approach. A operation can be called from just about anywhere in VS. If it were coded like my theoretical notepad clone, the main window must be millions of lines long: there are tons of operations in VS. Of course, VS is not coded like that. They use commands.

What if we wanted to make our open operation in the notepad clone a little more permanent? We’d probably want to take the code and move it into it’s own class that could be re-used across our whole app, independent of the window. You’ve essentially just made a command: separated the logic of the operation from the UI that invokes that operation. There would likely be more than one operation too, and if we did that to every operation, we’d probably see a lot of duplication in those classes. Duplication that can be removed by formalizing the reoccurring pattern. This idea really takes off when it’s built right in to your UI framework; the controls you use could know about commands, there could be a set of built-in commands that are common enough that they are worth implementing by the framework. Fortunately, Microsoft has done with WPF.

For complete background on commands in WPF, you should check out Jelle Druyts’s article. He explains it really well, and there’s basically nothing I can add that doesn’t repeat what Jelle already says.

Instead what I’ll do is show you what I did in BabySmash to reduce some of the code that Scott wrote, and that you’d have to write in your apps, and let the system to it for us. I’ll explain just enough about how commands work in WPF, but you should really read Jelle’s article. It’s ok, I’ll wait for you.

BabySmash lets a baby, or anyone, repeatedly mash the keyboard which makes fun things happen. That’s the main part of the app, but there are some ancillary things that all apps need, like settings and setting those settings, which I’ve covered already. We also need a way to open the dialog to set the settings. To open the options window, one has to press Ctrl-Shift-Alt-O. Scott sniffs for that in the "main loop" of his app, the KeyUp event handler. Perfectly fine really, there’s only one operation right now, but he may want to add more, then that KeyUp handler method will started getting hairy….er. Also, I’m a firm believer in methods doing one thing. Right now the KeyUp handler is doing many things.

private void Window_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
    //HACK: Why did I find the Windows Forms modifier keys classes to be so much more accurate?
    bool Alt = (System.Windows.Forms.Control.ModifierKeys & WinForms.Keys.Alt) != 0;
    bool Control = (System.Windows.Forms.Control.ModifierKeys & WinForms.Keys.Control) != 0;
    bool Shift = (System.Windows.Forms.Control.ModifierKeys & WinForms.Keys.Shift) != 0;


    if (Alt && Control && Shift && e.Key == Key.O)
    {
        e.Handled = true;
        Options o = new Options();
        o.ShowDialog();
        return;
    }

    numberOfShapes++;
    if (numberOfShapes > Properties.Settings.Default.ClearAfter)
    {
        numberOfShapes = 1;
        MainCanvas.Children.Clear();
    }

    PlayLaughter();
    ...
}

So let’s separate out the Options window opening code. To do that, as Jelle explains, we need to declare a command binding. We could do that in code, but let’s do it in XAML.

<Window x:Class="BabySmash.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Baby Smash by Scott Hanselman - http://www.hanselman.com/babysmash"
        Height="386" Width="601"  WindowStyle="None"
         Topmost="True" Activated="Window_Activated" Closing="Window_Closing"    
        
    AccessKeyManager.AccessKeyPressed="Window_AccessKeyPressed"
       KeyUp="Window_KeyUp" KeyDown="Window_KeyDown"
       Loaded="Window_Loaded"
        >
    <Window.CommandBindings>
        <CommandBinding Command="Properties" Executed="Properties_Executed"/>
    </Window.CommandBindings>
    <Grid>
        <Canvas x:Name="MainCanvas">
            
        </Canvas>
    </Grid>
</Window>

Here’s the Window1.xaml from BabySmash with a CommandBinding declared. I’m using the built-in command, ApplicationCommands.Properties. Technically, not semantically correct, but close enough for our purposes. The CommandBinding is basically saying when someone invokes the Properties command for this window, handle it in the Properties_Executed handler, shown below.

private void Properties_Executed(object sender, ExecutedRoutedEventArgs e)
{
   Options o = new Options();
   o.ShowDialog();
}

We’re almost ready to delete some of Scott’s code. Now we have to hook up a way to invoke the command. If there were buttons or menu items in BabySmash, we could just set the Command property on them and WPF takes care of it all. It doesn’t, so we have to do a little more. We have to create an InputBinding for the Ctrl-Shift+Alt+O shortcut key, known in WPF as an InputGesture.

<Window>
    <Window.CommandBindings>
        <CommandBinding Command="Properties" Executed="Properties_Executed"/>
    </Window.CommandBindings>
    <Window.InputBindings>
        <KeyBinding Gesture="CTRL+ALT+SHIFT+O" 
                    Command="{x:Static ApplicationCommands.Properties}" />
    </Window.InputBindings>
    <Grid>
        <Canvas x:Name="MainCanvas">
            
        </Canvas>
    </Grid>
</Window>

Note the two ways in XAML to declare the command. The first one, in the CommandBinding element is allowed because it’s a built-in command. The second way will work for your custom commands as well. That’s it.

Now the KeyUp handler can be simplified by deleting code; as Scott pointed out, always a good thing.

private void Window_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
    numberOfShapes++;
    if (numberOfShapes > clearAfter)
    {
        numberOfShapes = 1;
        MainCanvas.Children.Clear();
    }

    PlayLaughter();
    ...
}

I’ll leave it as an exercise for you following at home to add the close command and an InputBinding for ALT-F4. I didn’t test thoroughly but this can handle the problem that Scott noticed with multiple monitors.

StaticResource does not mean static

My post about BabySmash got hanselmanned. There are some questions in the comments on that post that are worth addressing in another couple posts, so here’s the first. For background, we have Scott’s follow up post, describing how he changed the code because of my post.

In Scott’s post, Configuration with DataBinding, he wrote the following:

Next, we tell the Grid that’s laying out the controls that we have some static data we’ll be using and we call it "settings" because that’s the class name.

<Grid DataContext="{StaticResource settings}">

There are a few misunderstandings in this statement that I’d like to clarify, since this is a learning experience and all.

There are two big WPF concepts here, DataContext and StaticResource. I’ll tackle StaticResource here. Consider the XAML below:

   1: <Window x:Class="WpfApplication1.Window1"
   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:     xmlns:System="clr-namespace:System;assembly=mscorlib"
   5:     SizeToContent="WidthAndHeight">
   6:     <Window.Resources>
   7:         <System:String x:Key="s">Hello</System:String>
   8:         <System:String x:Key="i">42</System:String>
   9:     </Window.Resources>
  10:     <StackPanel>
  11:         <TextBlock Text="{StaticResource s}" />
  12:         <TextBlock Text="{DynamicResource i}" />
  13:     </StackPanel>
  14: </Window>

This is the world’s tiniest window. I have two TextBlocks – think of TextBlock as a simple label, for now – one below the other, whose text is set to some string values. I’ve declared the strings in the window’s ResourceDictionary, through the Window.Resources property. The Resources property is declared on FrameworkElement, from which all controls in WPF inherit, so it’s on every WPF control. The StackPanel has a ResourceDictionary, the two TextBlock’s do, the App object (not shown) does, and the system does too.

A ResourceDictionary is basically a giant hashtable. You can store any .NET object you want, like I did above. You can do this from code as well, which perhaps may be more appropriate (since XAML tends to obscure things; remember: anything in XAML can be done in [way more verbose] code):

   1: public class Window2 : Window
   2: {
   3:   public Window2()
   4:   {
   5:      //declaring the same resources in code
   6:      this.Resources.Add("s", "Hello");
   7:      this.Resources.Add("i", "42");
   8:   }
   9: }

I have two strings sitting in a ResourceDictionary. Now, I want to access them. Let’s do that in code first. In the code below, I create my StackPanel, add my TextBlocks to it, and set the values on them. Here’s the not-quite-equivalent code version of the XAML declared at the beginning.

   1: public Window2()
   2: {
   3:    //declaring the same resources in code
   4:    this.Resources.Add("s", "Hello");
   5:    this.Resources.Add("i", "42");
   6:  
   7:    StackPanel stackPanel = new StackPanel();
   8:    //setting the textblocks' text property to resources 
   9:    TextBlock textBlock1 = new TextBlock();
  10:    textBlock1.Text = (string) this.Resources["s"];
  11:    
  12:    TextBlock textBlock2 = new TextBlock();
  13:    textBlock2.Text = (string) this.Resources["i"];
  14:  
  15:    stackPanel.Children.Add(textBlock1);
  16:    stackPanel.Children.Add(textBlock2);
  17:  
  18:    this.SizeToContent = System.Windows.SizeToContent.WidthAndHeight;
  19:    this.Content = stackPanel;
  20: }

I say not quite equivalent because the XAML is doing something slightly different. In the code version, I access the resource directly. In XAML, I’m telling WPF that the values I want for the Text properties are resources, one static and one dynamic (which I’ll get to in a moment). WPF will then move up the control hierarchy (I’m not sure exactly, but I think it moves up the logical tree) and check each ResourceDictionary for the key given. So it’ll check the StackPanel’s resources, then the Window’s. If it wasn’t in the Window’s resources, it would move up to the App resources, and finally to System resources. Resources are really important in WPF; it is where things like Brushes, Colours, Styles and Templates are put. If you were making a skinnable app, you’d make heavy use of resources.

Now, let’s clear up what the StaticResource does. Here’s the relevant XAML again:

<TextBlock Text="{StaticResource s}" />
<TextBlock Text="{DynamicResource i}" />

The curly braces means this is a MarkupExtension, a XAML-only concept that allows us as developers to be slightly more expressive than plain old XML allows. The meaning of static in this case may be clearer when juxtaposed with it’s brother, they DynamicResource. There is a class behind these two, StaticResourceExtension and DynamicResourceExtension. You could try writing the equivalent code; I did, and it didn’t work, but in the docs there is the ominous warning that this is used by the XAML subsystem and shouldn’t be called by humans.

The difference between StaticResource and DynamicResource is how they are accessed by WPF. The semantics of StaticResource are "just read this value once, and don’t check for changes." It’s static as in not moving, not as it is in C#. Note that the two objects in the window’s resources are plain old string instances.  StaticResources are good for things that don’t change, like Brushes or Styles, or read-only data. It’s unfortunate from a learning perspective that the data in BabySmash was static in the C# sense as well, but it’s just a coincidence, honest.

DynamicResource on the other hand is a little more intensive for WPF, because it will track changes to the ResourceDictionary. So if the value of a DynamicResource changes, WPF knows about it and updates the control accordingly. This is good for data that changes, obviously.

Let’s expand the XAML just a bit, and add a button with a click handler. In the click handler, let’s update the value keyed with "i". Run the code, click the button and watch as 42 becomes world. And you don’t have to write anything to make this happen.

<StackPanel>
    <TextBlock Text="{StaticResource s}" />
    <TextBlock Text="{DynamicResource i}" />
    <Button Click="Button_Click">Click me</Button>
</StackPanel>
 
private void Button_Click(object sender, RoutedEventArgs e)
{
    this.Resources["i"] = "world";
}