Monthly Archives: February 2012

Data binding in WPF – converters

In the last post, we saw how to use data binding to synchronize the value of a data field with the text displayed in a TextBox. In that example, the binding was relatively straightforward, since the type of data (an int) can be displayed as text in a TextBox, as WPF does an automatic conversion from a numeric type to text.

However, data binding is much more flexible than this. Pretty well any property of a control can be bound to any type of data. If WPF doesn’t provide an automatic conversion, though, you’ll need to write a converter yourself to fix the binding.

We’ll look at a couple of examples here. First, recall that the program we were working on in the last post allowed the user to step through the integers and test if each was either prime or perfect. The interface to the program looks like this:

The ‘Factors’ box displays the number of factors (excluding 1 and the number itself) that ‘Number’ has; ‘Sum of factors’ adds up Number’s factors (this time, including 1). If ‘Factors’ is zero, the number is prime, while if ‘Sum of factors’ equals Number, the number is perfect. We’d like to colour-code these two boxes so that Factors is LightSalmon if the number is prime, and Sum of factors is LightSeaGreen if the number is perfect. This requires binding a numerical value (in the case of a prime number) or a logical value (in the case of a perfect number) to a Brush used to paint the background of a TextBox. Not surprisingly, there is no built-in conversion between these types of data, so we’ll need to write one.

A data binding converter must be a class that implements the System.Windows.Data.IValueConverter interface. This interface requires us to write two methods: Convert() and ConvertBack(). Here’s the code for NumberToBackgroundConverter, which does the required conversion in our program:

  using System.Windows.Data;
  using System.Windows.Media;
  ......
  class NumberToBackgroundConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      if (parameter.ToString().Equals("IsPerfect"))
      {
        bool isPerfect = bool.Parse(value.ToString());
        if (isPerfect)
        {
          return Brushes.LightSeaGreen;
        }
        else
        {
          return Brushes.Transparent;
        }
      }
      else if (parameter.ToString().Equals("NumFactors"))
      {
        int number = int.Parse(value.ToString());
        if (number == 0)
        {
          return Brushes.LightSalmon;
        }
        else
        {
          return Brushes.Transparent;
        }
      }
      return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      throw new NotImplementedException();
    }
  }

Notice the two using statements at the start; they are required for the IValueConverter interface and the Brushes objects, respectively.

The Convert() method is the only one we need to implement, since we won’t be converting back from a Brush to a data value. The first argument to Convert(), ‘value’, is the object from which conversion is taking place, and the object returned from Convert() is the object to which conversion is done. These are both defined as object type, which means that a converter can convert any type of object to any other type (since ‘object’ is the base class of all C# classes).

The second argument, ‘targetType’, is the data type of the target, which is sometimes useful in deciding what object to generate as the return value. We don’t use it here. The third argument, ‘parameter’, is a parameter that can also be used to decide what type of conversion to do. In this example, the parameter is used to decide whether we’re dealing with a prime number or a perfect number. We’ll see how this parameter is specified in a minute, when we consider attaching the converter to a control’s property.

The final argument, ‘culture’, is used in globalization, as it allows things like date and time strings to be formatted appropriately for a given country. Again, we won’t be using this here.

The rest of the code is fairly obvious. We test to see if the parameter is “IsPerfect”. If so, ‘value’ will be a bool indicating whether the current number is perfect. If it is, we return a LightSeaGreen brush; if not, we return a Transparent brush so the regular background colour of the ‘Sum of factors’  TextBox shows through. The background colour of TextBoxes and other controls depends on the overall Windows theme the user has adopted, so we don’t want to anticipate the choice by specifying a particular colour.

The second part of Convert() deals with the prime number box. If parameter is “NumFactors”, ‘value’ will be an int, so we check to see if it’s zero. If so, we return a LightSalmon brush.

That’s it for the converter class. Now, how do we use it?

In Expression Blend (EB), select the sumFactorsTextBox. In its properties panel, find Background and click on the little square to the right. This will bring up a context menu, from which you select ‘Data binding’. Select the data field to act as the source in the same way as we did in the previous post when binding data to the text in a TextBox. In this case, we want to bind the background colour to the IsPerfect bool data field in the PrimePerfect class, so add that class to the Data Sources in the Data Field tab (if it’s not already there), and then select the IsPerfect field on the right. You will need to select ‘All properties’ in the show box at the lower right to make these data fields visible.

Next, expand the panel at the bottom by clicking on the downward pointing arrow. Click the … box to the right of ‘Value converter’ and select the NumberToBackgroundConverter class. Enter “IsPerfect” in the ‘Converter parameter’ box, then click OK. This completes the data binding, and if you run the program at this point, the Sum of factors box should turn green whenever you hit a perfect number (6 is the lowest one; 28 is the next).

The procedure for the ‘Factors’ box is just the same. This time, bind the Background to the NumFactors field in PrimePerfect. Use the same converter class, but give the parameter as “NumFactors”. Now both boxes should light up at the correct times as you step through the numbers.

As a final example, we would like the Dec button to become disabled if Number reaches 2, since we don’t want to look at any integers smaller than 2. To do this, we first write another converter class:

using System.Windows.Data;
......
  class NumberToEnabledConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      int number = int.Parse(value.ToString());
      if (number <= 2)
      {
        return false;
      }
      else
      {
        return true;
      }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      throw new NotImplementedException();
    }
  }

This time the input ‘value’ is an integer and the return object is a bool (false if the button is disabled, true otherwise). We check if ‘value’ is <= 2 and disable the button if it is.

In EB, the binding proceeds just as before. Select decButton, find its IsEnabled property (in Common Properties in the Properties panel), bind this to the Number field in PrimePerfect and attach a converter, specifying the converter class as NumberToEnabledConverter. No parameter is needed this time. Now each time Number gets reduced to 2, Dec is disabled.

There is still one flaw in this program: it is possible to select the Number TextBox and type in a value less than 2 (in fact you can enter a negative number). You can even type in any old text, though if you do this and then hit tab to remove the focus from the TextBox, you’ll see a red outline appear around the box, indicating invalid input (which admittedly isn’t very user-friendly – what does the red box mean, and what is correct input?). To fix these problems, we need to investigate validation, but that’s a topic for another post.

Source code available here.

Advertisements

Simple data binding in WPF: 1 – Binding controls to objects

We’ll start having a look at data binding in WPF. Briefly, data binding is the ability to bind some property of a control (such as the text in a TextBox) to the value of a data field in an object. (More generally, you can bind controls to other data sources such as databases, but that’s more advanced.) The idea, and the need for it, are best illustrated with an example.

Suppose we want a little program that allows you to step through the integers and test each one to see if it’s a prime number or a perfect number. In case you’ve forgotten, a prime number is one whose only factors are 1 and the number itself, so 2, 3, 5, 7, 11, 13, 17 and so on are the first few prime numbers. A perfect number is one where the sum of all its factors (including 1 but excluding the number itself) equals the number itself. The smallest perfect number is 6, since its factors are 1, 2 and 3, and 1+2+3=6. The next perfect number is 28, and after that they get quite large, and very rare.

The interface for the program might look like this:

The number being considered is shown at the top. The Factors box shows the number of factors (excluding 1 and the number itself) that number has; thus a number with zero factors is prime. The ‘Sum of factors’ box shows the sum of the number’s factors (including 1, but excluding the number). A number whose ‘Sum of factors’ equals the number itself is therefore perfect.

The program should paint the background of the ‘Factors’ box LightSalmon if the number is prime, and the background of the ‘Sum of factors’ box LightSeaGreen if the number is perfect.

The Reset button resets Number to 2. The Dec button decrements Number by 1; Inc increments Number by 1, and Exit quits the program. Note that the Dec button also becomes disabled when Number is 2, since we don’t want to consider any numbers less than 2.

If the only programming technique you knew about was event handling, you can see that you would need to add handlers for each button’s Click event, and these handlers would need to update Number and the values displayed in the various TextBoxes. You would also need to handle the TextChanged event in the Number TextBox so if the user typed in a new number it would update the other boxes. Quite a bit of back-and-forth coding would be needed to keep everything synchronized.

Data binding allows the value displayed by a TextBox, or in fact pretty well any property of any control, to be bound to a data value, so that changing the data value automatically updates the property, and changing the property can also update the data value.

Let’s start with the simplest case: binding the value displayed by a TextBox to a data field in an object. To work on this project, we’ll use Expression Blend (EB) for the design and binding work, and Visual Studio (VS) for writing the classes we need to support the data binding. I’ve built the user interface using EB and won’t go into the details here; you can look here for an introduction to using EB to build interfaces. If you want the XAML code, you can download the project files; see the end of this post for the link.

We’ll need a class for storing the details of the number being considered, and for calculating the factors of that number. We’ll call that class PrimePerfect, and create it in VS. It’s a pretty standard class, except for one thing: it must be able to notify the controls when any of the relevant data fields are changed so they can be updated. In data binding, the way this is done is by writing a class that implements the INotifyPropertyChanged interface. The beginning of PrimePerfect therefore looks like this:

  using System.ComponentModel;
  ......
  class PrimePerfect : INotifyPropertyChanged  // in System.ComponentModel
  {
    public event PropertyChangedEventHandler PropertyChanged;
    protected void Notify(string propName)
    {
      if (this.PropertyChanged != null)
      {
        PropertyChanged(this, new PropertyChangedEventArgs(propName));
      }
    }
  ......

Note the using statement at the top; it is required for notification code.

Implementing INotifyPropertyChanged requires that we declare an event handler for PropertyChanged, as we’ve done on line 5. The Notify() method on line 6 takes a string parameter which is used to identify which property has changed, and the event handler is then called, passing along this parameter.

The rest of the class consists of standard code, defining the properties and calculating the factors of the number. A typical property looks like this:

    int numFactors;
    public int NumFactors
    {
      get { return numFactors; }
      set
      {
        numFactors = value;
        Notify("NumFactors");
      }
    }

The property contains the usual ‘get’ and ‘set’ clauses, but note that in the ‘set’, a call to Notify() is made, passing along a string identifying which property has been set. This property string is used to bind the text field of a TextBox to the value of NumFactors.

To see how this is done, we return to EB (make sure you save and build the project at this point, so the updates to the PrimePerfect class are available to EB). We’ll add the binding between the factorsTextBox (that displays the current value of NumFactors) and the NumFactors data field in PrimePerfect. In EB, select factorsTextBox. In ‘Common Properties’ in the right panel, find the Text entry. Click on the little square to the right of the entry, and select ‘Data binding’ from the context menu. In the dialog box that appears, click “Data field” at the top, then “+CLR Object”. This brings up another dialog that shows the available data sources for the binding. Find the namespace containing the PrimePerfect class (in the project here, I’ve called it PrimePerfectBinding), and select the PrimePerfect class, then OK. You should now see PrimePerfectDataSource appear in the Data sources column. Click on it, and PrimePerfect should appear in the Fields list on the right. Open it and select NumFactors from the list (if you can’t see it, try setting ‘Show’ to ‘All properties’ in the combo box at the bottom). Click OK and the binding is complete.

If you now look at the XAML code for factorsTextBox, you should see Text=”{Binding NumFactors}” as one of the attributes.

If you’ve been following faithfully, you’ll probably have noticed that although we’ve defined the PrimePerfect class and added notification code to it, and also added a binding to factorsTextBox, we haven’t actually created an instance of PrimePerfect yet. To remedy this, go to the C# code-behind file for MainWindow, and add a couple of lines to it as follows.

    PrimePerfect primePerfect;
    public MainWindow()
    {
      InitializeComponent();
      primePerfect = new PrimePerfect();
      baseGrid.DataContext = primePerfect;
    }

You’ll see we create an instance of PrimePerfect (its default constructor sets Number = 2). However, we’ve also added a cryptic line in which a DataContext is set to this object. What’s a DataContext?

The data context is an object that serves as the source of the data in a binding. When a control, such as factorsTextBox, was assigned a binding, all we did was specify the name of the data field (“NumFactors”) to which it is bound. We didn’t give the TextBox any information about where it should look for this data. The WPF data binding mechanism takes care of this by having a control with a data binding look for a data context. It will look first in the control itself. If a data context isn’t found there, it will look in the parent container of that control, and so on until it reaches the root container (usually the Window). What we’ve done here is attach a DataContext to the Grid that contains all the controls in the interface (‘baseGrid’ is the name of that Grid object). This means that all controls in that Grid that have data bindings will look in the same PrimePerfect object for their data. This completes the data binding process for factorsTextBox.

To get the program to run at this point, we need to complete the code in PrimePerfect so that it calculates NumFactors and SumFactors for the current Number. This code doesn’t have any bearing on the data binding so we won’t list it here, but if you want to see how it’s done, just download the source code and have a look at it.

If you run the program at this point, you should see the Factors TextBox display the current value of NumFactors, which is 0 (since 2 is the starting Number, and it’s prime). The Number and Sum of factors TextBoxes won’t show anything unless you go through the same process and bind them to the corresponding properties in PrimePerfect. There’s nothing new involved in doing this, so you can either try it yourself or just look at the source code to see how it’s done.

So far, we haven’t added any event handlers to the buttons, so let’s finish with that. We can add handlers for the buttons by double clicking on the Click event for each button in EB. This generates event handlers in MainWindow.xaml.cs, and we can enter some code in them as follows.

    private void incButton_Click(object sender, RoutedEventArgs e)
    {
      primePerfect.Number++;
    }

    private void decButton_Click(object sender, RoutedEventArgs e)
    {
      primePerfect.Number--;
    }

    private void exitButton_Click(object sender, RoutedEventArgs e)
    {
      Application.Current.Shutdown();
    }

    private void resetButton_Click(object sender, RoutedEventArgs e)
    {
      primePerfect.Number = 2;
    }

There’s nothing surprising here. The three buttons that change the value of Number do so with a single line each. Now if you run the program, you’ll see that clicking on each button does change the value of Number, and also updates Factors and Sum of factors. Why? Because whenever we change the value of Number, we are calling the ‘set’ method of the Number property in PrimePerfect, and this calls code that recalculates NumFactors and SumFactors. All of this fires a Notify event for each property, so any control that is bound to that property gets updated automatically.

At this stage, we have a program that allows us to step through the numbers and display NumFactors and SumFactors for each number. However, we still haven’t added the colour-coding of the textboxes when we find a prime or perfect number, and the Dec button will allow us to set Number lower than 2, which may have disastrous consequences if the number goes negative. We can fix all these problems using data binding as well, but that’s a topic for the next post.

Code for this post is here.

Mutual recursion in Clojure – the trampoline

We’ve seen how recursion can be implemented efficiently (that is, without stack overflow), and also how the loop special form can be used to simulate a loop in an imperative language. These techniques work well if we’re dealing with simple recursion, in which a single function calls itself.

A more complex case is mutual recursion, in which two or more functions call each other recursively. Since recur always directs a function to call itself, it can’t be used in mutual recursion, so we can’t use it to avoid stack overflow. Most simple examples of mutual recursion are somewhat contrived, and the one about to be given is no exception, but it should serve to get the point across.

Suppose we are given a number and want to alternate between taking the square root and dividing by 2 until the result is less than 1. We can set up one function for taking the square root and another for dividing by 2, and use mutual recursion to perform the desired task:

(declare div2-recur)
(defn sqrt-recur [n]
  (do
    (println "sqrt-recur:" n)
    (if (< n 1)
      n
      (div2-recur (Math/sqrt n)))))

(defn div2-recur [n]
  (do
    (println "div2-recur:" n)
    (if (< n 1)
      n
      (sqrt-recur (/ n 2)))))

On line 1, we explicitly declare the second function div2-recur since it is referred to in the first function, and the Clojure reader will complain about an undefined symbol unless we declare it.

The sqrt-recur function takes a number n as an argument, prints it out, then tests if it is less than 1. If so, n is returned and the function ends. If not, a recursive call is made to div2-recur, passing the square root of n as the argument.

div2-recur works the same way, except it passes n/2 back to sqrt-recur. We can test the functions at the REPL:

=> (sqrt-recur 5)
sqrt-recur: 5
div2-recur: 2.23606797749979
sqrt-recur: 1.118033988749895
div2-recur: 1.057371263440564
sqrt-recur: 0.528685631720282
0.528685631720282

The number in the last line is just the final value of n returned from the last call to div2-recur.

However, because we’re not optimizing the recursive calls, if we give this program a large enough number, it will cause a stack overflow. The solution to this problem is not to use recur, as we did with single recursion, but rather a function called trampoline. To do this, we need to make a slight modification to each function. The revised functions are:

(declare div2-recur2)
(defn sqrt-recur2 [n]
  (do
    (println "sqrt-recur2:" n)
    (if (< n 1)
      n
      #(div2-recur2 (Math/sqrt n)))))

(defn div2-recur2 [n]
  (do
    (println "div2-recur2:" n)
    (if (< n 1)
      n
      #(sqrt-recur2 (/ n 2)))))

Apart from changing the names of the functions, the only change we made is the addition of a # in the last line of each function. This converts what was a function call in the first version to an anonymous function definition in the revised version. That is, instead of a recursive call being made to div2-recur2 from sqrt-recur2, an anonymous function is returned from sqrt-recur2. As it stands, there is no recursive call between the two functions any more. You can verify this by calling either function directly at the REPL:

=> (sqrt-recur2 5)
sqrt-recur2: 5
#<FunctionTest$sqrt_recur2__1356$fn__1358 .FunctionTest$sqrt_recur2__1356$fn__1358@5506d>

The first println in sqrt-recur2 prints out its value, and then we get a cryptic line of output which is Clojure’s internal representation of the anonymous function in the last line of sqrt-recur2.

However, if we use the built-in Clojure function trampoline, the functionality is magically restored:

=> (trampoline sqrt-recur2 5)
sqrt-recur2: 5
div2-recur2: 2.23606797749979
sqrt-recur2: 1.118033988749895
div2-recur2: 1.057371263440564
sqrt-recur2: 0.528685631720282
0.528685631720282

So what exactly is trampoline doing? We can find out by looking at its code (available in the clojure.core sourcecode listings):

(defn trampoline
  ([f]
     (let [ret (f)]
       (if (fn? ret)
         (recur ret)
         ret)))
  ([f & args]
     (trampoline #(apply f args))))

The function can take either a single argument, or multiple arguments. Since we invoked it with 3 arguments, we’ll look at that bit (lines 7 and 8) first. trampoline assumes its first argument is a function (sqrt-recur2 in our example above), and it constructs an anonymous function which it then passes back to itself, thus causing the version of trampoline with a single argument to be called.

The anonymous function uses apply to apply the function f to the remaining arguments. In our example, the only remaining argument is 5, so sqrt-recur2 is applied to 5. However, look at what trampoline does with the function it is passed. The argument is tested to see if it is a function and, if so, recur gets the function ret to run, and passes whatever it returns as a recursive argument back into trampoline. In our example, calling sqrt-recur2 with an argument of 5 will return an anonymous function calling div2-recur2 with an argument that is the square root of 5. Thus trampoline receives another function as its argument in the recur, so it will call that function and pass its return value back into trampoline. Eventually, one of these function calls will return just a number (when that number is less than 1). At that point, the argument to trampoline will not be a function (rather, it’s just a number), so the recursion in trampoline stops, and the number itself is returned.

What has happened is that trampoline handles the mutual recursion by converting it into single recursion within the trampoline function, so that recur can be used to optimize the recursion and prevent a stack overflow. This is yet another example of the power of using first-class functions (functions that can be passed around as arguments to other functions).

One final note. Forcing the user to call this program by explicitly typing out a call to trampoline isn’t very friendly, so it’s a good idea to provide a wrapper that hides what’s going on. That’s easy enough to do by defining an auxiliary function:

(defn sqrt-div2 [n]
  (trampoline sqrt-recur2 n))

Now we can run the code by typing just (sqrt-div2 5).

Custom commands in WPF

We’ve looked at using built-in commands and providing bindings for built-in commands, so it’s time to have a look at creating a custom command from scratch. Conventionally, a Command implements the singleton design pattern, which means that in any running program, there should be at most one instance of the Command object in existence. The rationale behind this is that a Command represents a particular set of instructions which is fixed, but which can be called from a number of different sources or actions, such as the copy command which could be called from a menu, a toolbar button or by typing Ctrl+C.  All these actions should do the same thing, so they should all refer to the same Command object.

As such, we should create a Command object as a singleton. There are various ways this can be done in code, but we’ll look at just one here: declaring the new custom Command as a static object that is created in a static constructor (which is called once when the program starts, and that’s it). We create a new class for our custom Command, and its code looks like this:

  class CustomCommands
  {
    public static RoutedUICommand AquaButtonCommand;

    static CustomCommands()
    {
      InputGestureCollection aquaButtonInputs = new InputGestureCollection();
      aquaButtonInputs.Add(new KeyGesture(Key.A, ModifierKeys.Alt));
      aquaButtonInputs.Add(new MouseGesture(MouseAction.WheelClick, ModifierKeys.Control));
      AquaButtonCommand = new RoutedUICommand("Aqua", "AquaButton", typeof(CustomCommands), aquaButtonInputs);
    }
  }

The RoutedUICommand class is the WPF class for creating a routed command connected to a user interface object. Remember that a routed command follows the same routing rules as an ordinary event: starting at the root of the interface tree (typically the Window), each event first tunnels through the tree until it reaches the control that generated the event, and then bubbles back up the tree, visiting each control in the tree along the way in both directions. A ‘preview’ handler for the event can be placed at any point on the path, and it will be fired as the Command tunnels down from the root; a regular handler will be fired as the Command bubbles back up to the root.

We’ve called the custom Command AquaButtonCommand, since it has the frivolous effect of changing part of the UI to the colour aqua. This seemed a slighly more picturesque way of illustrating where the events were handled than the usual method of printing a message to the console.

This example shows how to attach a KeyGesture and a MouseGesture to the Command. (We’ll attach the Command to the ‘Aqua’ button later.) The code here causes the Command to be executed when the Alt+A key combination is pressed, or when the Ctrl key is held down and the mouse wheel rotated (somewhat confusingly, the WheelClick mouse action isn’t a press of the wheel; it’s a rotation of the wheel).

In the RoutedUICommand constructor call on the last line, the first argument is a string that can be used elsewhere as a description of the command (for example, as text on a Button). The second argument is a string that is used in the internal representation of the Command (as in serialization). The third argument is the data type of the enclosing class, and the last argument is the InputGestureCollection we’ve just created.

So much for creating the custom command. Once you have the new command, it can be used in the same way as any of the built-in commands, so there are no surprises here. However, one thing we haven’t yet considered is how to enable and disable a command from within the code.

In our first example, where we attached cut, copy and paste commands to a TextBox, the TextBox did all the work of deciding when a command was enabled or disabled. If there was some text on the clipboard, the paste command was enabled; if some text was selected in the TextBox, cut and copy were enabled and so on. Most commands don’t have this functionality built in so it’s up to the programmer to decide when to enable and disable a command.

We’ll attach our custom AquaButtonCommand to the Button labelled ‘Aqua’, and then do a few other things with the command. The code looks like this:

      customButton.Command = CustomCommands.AquaButtonCommand;
      customButton.Content = CustomCommands.AquaButtonCommand.Text;
      CommandBinding customBinding = new CommandBinding(CustomCommands.AquaButtonCommand);
      customBinding.CanExecute += new CanExecuteRoutedEventHandler(aquaBinding_CanExecute);
      customBinding.Executed += new ExecutedRoutedEventHandler(aquaBinding_Executed);
      CommandBindings.Add(customBinding);
      //customButton.CommandBindings.Add(customBinding);

On line 1, we attach the command to the button. On line 2, we use the descriptive text we specified when creating the command as the label for the Button. Line 3 creates a binding for the command in the usual way. We’ll look at line 4 in a minute. Line 5 specifies a handler for the Executed event, and line 6 attaches the binding to the Window object containing the whole UI. Line 7 is commented out for now.

The handler looks like this:

    void aquaBinding_Executed(object sender, ExecutedRoutedEventArgs e)
    {
      if (sender == customButton)
      {
        ((Button)sender).Background = new SolidColorBrush(Colors.Aqua);
      }
      else if (sender == this)
      {
        ((Window)sender).Background = new SolidColorBrush(Colors.Aqua);
      }
    }

The handler attempts to discover what the sender of the event is (either the Aqua button or the underlying window) and then sets the background colour of the sender to Aqua.

Now back to the CanExecute event, for which we specified a handler above. The handler looks like this:

    void aquaBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
      // WriteLine for testing when CanExecute is called...
      Console.WriteLine("aquaBinding_CanExecute");

      // Custom button becomes enabled when text is correct
      if (textBox1.Text.Equals("Enable"))
      {
        e.CanExecute = true;
      }
    }

The CanExecute event is generated whenever there is any interaction with any part of the UI. By default, if no handler is specified for this event, CanExecute is ‘true’, so the Aqua button would be enabled. However, as soon as we attach a handler for the event, the default value is ‘false’, so the Aqua button starts off disabled here.

Since it’s difficult to know when the event happens, we’ve written a WriteLine() statement that prints a message each time the handler is called. If you run the project as a console application, you’ll see this message printed every time you click anywhere in the window with the mouse, or any time you type on the keyboard. The handler basically gives you the chance to enable or disable its associated command in response to any interaction with the program. To illustrate this, we enable the command whenever textBox1 contains the text “Enable”. If you start up the program, you’ll note that the Aqua button starts off disabled. If you delete the existing text in textBox1 and then type Enable, you’ll see the button become enabled after you type in the last letter “e”. At this point, the keyboard and mouse shortcuts also kick in, and you can run the command either by pressing the Aqua button, typing Alt+A, or Ctrl+MouseWheel. Since the handler was attached to the Window, it is the Window’s background (visible as the unsightly gap between the two TextBoxes) that turns aqua.

If we now disconnect the binding from the Window and attach it to customButton instead (comment out line 6 and uncomment line 7 in the code dealing with the binding above), then the command can be fired only if the button is pressed directly or else it has the keyboard focus (you can tab through the controls until it gets the focus). Pressing the button now causes the button’s background to become aqua, rather than the Window’s, since the button is now the sender of the command. (Curiously, when the button has focus, the Alt+A key combination will fire the command, but the Ctrl+MouseWheel gesture won’t. Not sure why…)

If you attach the binding to both the Window and the button, then the sender of the command is the Window if the button doesn’t have focus, and the button if it does have focus, as you might expect.

Code available here.

Commands in WPF

In addition to standard event handling, WPF offers a specialized type of handler called a Command. There’s some debate about how useful the Command is, compared to the ordinary event handler, but they do offer some nice features so they are worth a mention.

There are a number of commands that appear in many applications, and WPF’s Command classes provide ready-made versions of a number (144 to be exact) of them. Some of the most common Commands are those associated with text editing, such as copy, cut and paste. We’ll begin with a little application that illustrates how these actions can be handled using Commands.

Create a new project in Expression Blend or Visual Studio, and create a layout similar to that shown:

This layout is built on a DockPanel, with a Menu and its associated MenuItems docked to the top, a ToolbarTray and its Buttons docked to the left, and two TextBoxes docked to the bottom. The ugly gap between the two Textboxes is there for a reason, as we’ll see shortly.

The Edit menu contains the 3 edit commands: cut, copy and paste. Obviously we’d like each of these menu items to do the same thing as the corresponding button in the toolbar. We could just create an event handler for, say, the Copy button and then point the menu item at the same handler. However, WPF’s ApplicationCommands class contains these 3 (and quite a few other) commands ready-made. We’ll have a look at how you can use these commands out of the box first, before looking in a bit more depth at how they work, and how you can create your own command.

You can attach a Command to a UI object either by editing the XAML or the C# code. In XAML, you can edit the Button entries to look like this:

				<Button x:Name="cutButton" Content="Cut" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="75" Command="ApplicationCommands.Cut"/>
				<Button x:Name="copyButton" Content="Copy" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="75" Command="ApplicationCommands.Copy"/>
				<Button x:Name="pasteButton" Content="Paste" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="75" Command="ApplicationCommands.Paste"/>

You can add similar Command labels to the corresponding MenuItems in XAML as well.

In C#, you can insert a line such as this for cutButton:

cutButton.Command = ApplicationCommands.Cut;

If you run the program at this point (you should download and run the program if you aren’t building it yourself), you’ll discover that you can select text in either textbox and use either the toolbar buttons or the MenuItems to cut, copy and paste the text. You should also notice that if no text is selected in either textbox, the Cut and Copy Buttons and MenuItems are disabled. The Buttons and MenuItems are also able to tell which textbox to apply their operations to, as it is the textbox that had the keyboard focus before the Button or MenuItem was selected.

This semi-magical behaviour is due to the way a TextBox is designed. In order to understand why things Just Work with the cut, copy and paste buttons, and also how to deal with other Commands and even define your own, we need to delve a bit more deeply into what’s going on underneath. We’ll do that in the next post.

Code available here (ignore everything except the cut, copy and paste buttons and menu items for now).

Commands, targets and bindings

In the last post, we saw how to use some built-in WPF Commands to implement behaviour such as cut, copy and paste in TextBoxes. In that example, most of the functionality is already coded into the TextBox control for us, so we had very little work to do. To use Commands in any more complex situation, we need to understand a bit more about how they work.

There are four main components needed in the implementation of a Command. First, there is the Command itself. A Command object contains some basic information to be associated with the command that it will ultimately run, such as any input gestures (keyboard shortcuts or mouse actions, usually) associated with the Command. All the 144 built-in Commands provided by WPF are objects of this type. Some, such as copy, have some input gestures (Control+C for copy) pre-defined, while others do not. For now, we’ll consider only these given Command objects, and consider custom-made Commands later on.

Second, a Command needs a source, which is the object that generates the command. A command source is usually some UI element such as a Button or MenuItem. For example, a Button can be pressed to initiate a copy action.

Third, we need a target, which is an object on which the Command will act. In the case of the copy action, the target must be some control that contains something we can copy, such as text in a TextBox.

Finally, the guts of a Command are contained in a CommandBinding. A CommandBinding contains the event handlers that are called when the command is run, or when we need to check if a command is able to be run. Each UI control has a collection of CommandBindings, so that more than one Command can be associated with a given control. Conversely, we can also associate one Command with more than one control (as with the copy command being associated with both a toolbar button and a menu item).

Here’s a reminder of the interface we used in the last post:

Returning to our simple example from the last post, we saw there that all we did was attach a Command object to each Button and MenuItem. We didn’t specify any command targets or command bindings, so how did the program know what to do?

The answer comes in two parts. First, if no target is specified for a Command, the control that last had the keyboard focus before the Command was invoked is taken as the target. To see this, select some text (e.g. from Notepad) into the clipboard before starting up the program. When the program starts, none of its controls has the keyboard focus and you’ll see that the Paste button and menu item are disabled, even though there is something on the clipboard that could be pasted. When you click in either TextBox, the Paste button becomes enabled, since that TextBox has now become the Command target for the Paste command.

The CommandBindings for paste, cut and copy are pre-written when the target is a TextBox, so we don’t need to worry about them. With other Commands, things aren’t quite so simple.

To see how the other bits of a Command work, we’ll do some experiments with the Find button. Although the Find command is one of WPF’s built-in Commands, it doesn’t have pre-written bindings, so we need to do some work ourselves. For simplicity, we’ll work entirely in the C# code file. In the MainWindow() constructor, we’ll add the following at the end:

      findButton.Command = ApplicationCommands.Find;
      //findButton.CommandTarget = textBox1;
      CommandBinding binding = new CommandBinding(ApplicationCommands.Find);
      binding.Executed += new ExecutedRoutedEventHandler(binding_Executed);
      //findButton.CommandBindings.Add(binding);
      //textBox1.CommandBindings.Add(binding);

We’ve assigned the Find command to findButton. Ignoring the commented lines (we’ll use them later), we next create a CommandBinding associated with Find. We then provide a handler for the Executed event, which is run when the command is executed. For now, we don’t add this binding to any control, so it isn’t actually used yet.

The handler looks like this:

    void binding_Executed(object sender, ExecutedRoutedEventArgs e)
    {
      MessageBox.Show("Find dialog");
    }

All it does is display a MessageBox.

Now, according to what we’ve just said, since we haven’t specified a command target for Find, it should use whatever has the keyboard focus when findButton is pressed. If you run the program and select a TextBox, you’ll see that Find remains disabled. Why does this happen? After all, with Paste, the button became enabled as soon as we selected a TextBox.

The reason is that a TextBox has no built-in binding for Find, so even though the selected TextBox is being used as the command target, the lack of a binding means there are no instructions for Find to follow when it is invoked on the TextBox, so nothing can happen. As a result, the program won’t let you do anything that would try to invoke Find, and the button is disabled.

Next, try uncommenting the line:

textBox1.CommandBindings.Add(binding);

Now when we run the program, Find is disabled initially, but if we click in textBox1, it becomes enabled, and clicking on it brings up the MessageBox. However, it is only this TextBox that enables Find: clicking in textBox2 disables it again. This is because it is only textBox1 that has a binding for Find, so only it knows what to do when Find is invoked.

Next, try commenting out this line again, and uncommenting the binding to findButton, so the last two lines above become:

      findButton.CommandBindings.Add(binding);
      //textBox1.CommandBindings.Add(binding);

Now we find the Find button is enabled right from the start; we don’t need to click in either TextBox. This is because the Find button itself now knows how to handle the Find command, so it doesn’t need to rely on an implicit target in the form of a TextBox having the keyboard focus. In effect, findButton becomes its own target.

WPF is actually quite intelligent in being able to figure out when a control can handle a Command. If you now comment out the line beginning binding.Executed, for example, so that no handler is specified for the Executed event, the Find button will again be disabled even though a CommandBinding has been attached to findButton.

For our final experiment, use the following comment pattern in the above code:

      findButton.Command = ApplicationCommands.Find;
      findButton.CommandTarget = textBox1;
      CommandBinding binding = new CommandBinding(ApplicationCommands.Find);
      binding.Executed += new ExecutedRoutedEventHandler(binding_Executed);
      findButton.CommandBindings.Add(binding);
      //textBox1.CommandBindings.Add(binding);

We’ve now specified the target of findButton to be textBox1, but we’ve attached the binding to findButton. Now nothing you do can enable the Find button, since its target doesn’t know how to handle the Find command. Uncommenting the last line as follows again enables the Find button right from the start:

      findButton.Command = ApplicationCommands.Find;
      findButton.CommandTarget = textBox1;
      CommandBinding binding = new CommandBinding(ApplicationCommands.Find);
      binding.Executed += new ExecutedRoutedEventHandler(binding_Executed);
      //findButton.CommandBindings.Add(binding);
      textBox1.CommandBindings.Add(binding);

This might surprise you, since you might think that you’d need to give textBox1 the keyboard focus in order to enable the Find button. However, what has happened is that an explicit target has been given, and that target has a binding for the Find command attached, so the button is enabled at all times. It is only when no target has been set explicitly that the keyboard focus is used to select which target applies.

As you can see, knowing when a Command is enabled can be a bit tricky. Things get even worse when we consider enabling and disabling commands in the code, but we’ll look at that in the next post.

Code for this post is available here (but ignore the bits on custom commands, which will be covered later).

The for macro in Clojure

Although, strictly speaking, Clojure doesn’t have a ‘for’ loop in the sense of imperative languages like Java and C#, it does have a ‘for’ macro which provides, if anything, more functionality than the traditional ‘for’ loop. We’ll look at a few examples here.

The easiest way to get a feel for what for does is to look at a very simple example:

(defn squares-list [n]
  (for [i (range 1 (inc n))]
    (* i i)))

The first argument to for is a vector. Entries in the vector come in pairs. The first element in each pair is a symbol, and the second element is a list. for will bind the symbol to each element in the list in turn, and then execute the body of the for, which is the second argument to the for statement, and in the example given, is (* i i). In this example, then, the symbol i is bound to each number from 1 to n in turn, and for each such i, its square is calculated. The for returns a list of all the results it calculates, so in this case, we would get a list containing the squares of all the numbers from 1 to n.

=>(squares-list 5)
(1 4 9 16 25)

Nested for loops in imperative languages are easy to implement in Clojure as well. For example

(defn sum-of-squares [n]
  (for [x (range 1 (inc n))
        y (range (inc x) (inc n))]
    (+ (* x x) (* y y))))

The first pair in the vector lets x range over values from 1 to n. For each value of x, y then ranges over values from x+1 to n. The body of the for then calculates x^2 + y^2, and the final result is a list of all such values. For example

=> (sum-of-squares 5)
(5 10 17 26 13 20 29 25 34 41)

The elements in the result are 1*1+2*2, 1*1+3*3, 1*1+4*4, 1*1+5*5, 2*2+3*3 and so on.

At this stage, a single for in Clojure can be seen to be about as powerful as a traditional for, nested to any level we want. However, the Clojure for offers even more options, since each binding in the first argument vector can have one or more modifiers attached to it. We’ll look at a slightly more involved example to see how these modifiers work.

Suppose we want a list of all prime numbers less than a certain integer n. Remember that a prime number is one that is divisible only by 1 and itself. In order to generate the required list, we first need to be able to test whether a given number is prime. There are various ways this can be done, but a straightforward way is to try dividing the number by all numbers from 2 up to the number’s square root, since if it has any divisors, at least one of them must be less than or equal to the square root. We can do this in Clojure as follows.

(defn prime? [n]
  (let [denoms (range 2 (inc (int (Math/sqrt n))))
        zero-rems (filter #(zero? (rem n %)) denoms)]
    (zero? (count zero-rems))))

We use a let to define two lists. The first list, denoms, is a list of numbers from 2 to the greatest integer less than or equal to the square root. The notation Math/sqrt calls the Java sqrt() function in the Math class, which returns a double. The Clojure int function takes the integer part of a double.

The second list uses filter, which we saw earlier, to find all the numbers in denoms that divide n evenly (that is, with zero remainder). Recall that filter takes two arguments: the first is a unary predicate function (one that takes a single argument and returns true or false), and the second is a list of values which are applied one at a time to the predicate.

In this case, we’ve used an anonymous function as the predicate. The Clojure notation for an anonymous function is the hash sign # followed by a function body in parentheses. Arguments to the function are represented by the percent sign % followed by a number. Thus %1 refers to the first argument, %2 to the second and so on. A bare % without a number after it, as we’ve used here, also refers to the first argument. Thus the anonymous function here calculates the remainder when n is divided by its argument, and then tests if that remainder is zero.

The final line of prime? counts the number of elements in zero-rems and tests if that value is zero. If so, that means than no numbers divide n, so n must be prime.

With prime? defined, we can now look at finding all primes less than a given value. The code is

(defn primes-less-than [n]
  (for [x (range 2 (inc n))
        :when (prime? x)]
    x))

Here, x ranges from 2 to n, but this time there is a modifier in the form of a :when clause. This means that, for the current value of x, execution will continue past that point only when the :when condition is true. In this case, that means that execution will continue only when x is prime. If the :when condition isn’t true, all further code for that value of x is skipped, and the next value of x is obtained.

Running this example, we get

=> (primes-less-than 50)
(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47)

With nested fors, each binding can have its own modifiers. As a somewhat contrived example, consider

(defn triples-for-primes [n]
  (for [x (range 2 (inc n))
        y (range (inc x) (inc n))
        :when (prime? (+ x y))
        z (range (inc y) (inc n))
        :when (prime? (+ x y z))]
    (list x y z)))

This function will find all triples such that the sum of the first two numbers and the sum of all three numbers are both primes. This is a triply-nested loop, with x ranging from 2 to n, y from x+1 to n, and z from y+1 to n. For given values of x and y, values of z will be considered only if x+y is prime. If it isn’t, then everything after that point is skipped, and the next value of y is obtained.

The :when condition on z means that the body of the for (the ‘list’ statement) is run only if x+y+z is prime. The result is we get a list of all triples that satisfy both conditions. For example

=> (triples-for-primes 8)
((2 3 6) (2 3 8) (2 5 6) (3 4 6) (4 7 8) (5 6 8))

We see that 2+3 and 2+3+6 are both prime in the first triple, and so forth for the others.

As another example, suppose we want to find all perfect numbers up to a given value. A perfect number is one where the sum of all its divisors (including 1 but excluding the number itself) equals the number itself. The smallest perfect number is 6, sincd 1+2+3=6. The next is 28. For this, we need an auxiliary function that gives a list of all divisors of a number. This is similar to the function we wrote above for testing if a number is prime:

(defn divisors [n]
  (let [divs (range 1 (inc (quot n 2)))]
    (filter #(zero? (rem n %)) divs)))

We first form the list divs which contains all numbers from 1 up to n/2 (remember that quot does integer division, throwing away the remainder). We then use the same filter as in prime? above to find all numbers that divide n with no remainder.

Now we can find perfect numbers:

(defn perfect-less-than [n]
  (for [z (range 2 n)
    :when (= (reduce + (divisors z)) z)]
    z))

We test each value of z between 2 and n-1, subjecting it to a :when condition. In this condition, we first find a list of the divisors of z using the divisors function we just defined. Then we use Clojure’s reduce macro. reduce takes a binary function (a function that takes two arguments; the addition function +, here) as its first argument. It then applies this function to the first two elements of its second argument, which is a list. It takes the result of that operation and applies the function to it and the third argument of the list, and so on. Thus in this case, it adds up all the divisors of z. Finally, the :when condition tests if that sum is equal to the original number z. If so, then z is a perfect number.

Although this code does work, it’s not a very efficient way of finding perfect numbers. The first four perfect numbers are 6, 28, 496 and 8128, and the program will find them fairly quickly. The next known perfect number is 33550336, but the given code is far too inefficient to find this in any reasonable time.

for also has two other modifiers that can be applied to each binding. The first is :let, which works in much the same way as the regular let statement. It can be used to define symbols for later use within the for. For example, suppose we wanted to find all pairs of squares whose sum was prime:

(defn squares-for-primes [n]
  (for [x (range 2 (inc n))
        :let [xsquared (* x x)]
        y (range (inc x) (inc n))
        :let [ysquared (* y y)]
        :when (prime? (+ xsquared ysquared))]
    (list xsquared ysquared)))

After the x binding, we’ve used :let to define the symbol xsquared; similarly after the y binding we define ysquared. Also after the y binding, we use a :when to do the check on whether the sum of squares is prime. As a sample of the output:

=> (squares-for-primes 8)
((4 9) (4 25) (4 49) (9 64) (16 25) (25 36) (25 64) (49 64))

The final modifier allowed in for is :while. This means that execution should continue as long as the given condition is true. The difference between :when and :while is that if a :when condition is false, the current value of the variable within a given iteration is skipped and the next value of the variable within the same iteration is processed. If a :while condition is false, the iteration within which it occurred is terminated, with no further values being considered.

As another contrived example, suppose we are given a number x and we want to find pairs of numbers (x,x+1), (x, x+3), (x, x+5)… where the sum of each pair is always prime. (Note that pairs such as (x, x+2) never sum to a prime, since x+x+2=2x+2, which is always divisible by 2.) That is, we want to start with the pair (x, x+1) and then increase the second number of the pair by 2 successively until we hit a pair that doesn’t sum to a prime. (I did say this was contrived.) We can do that like this:

(defn consec-primes [n]
  (for [x (range 1 (inc n))
        y (range (inc x) (inc n) 2)
        :while (prime? (+ x y))]
    (list x y)))

The first variable x ranges from 1 to n, and the second starts at x+1 and ranges up to n, but in steps of 2 (if range has 3 arguments, the third is the step size). The iteration over y will continue until the :while condition fails, so for the first value of y where x+y is not prime, iteration over y will stop, and the next value of x will be selected. As an example:

=> (consec-primes 8)
((1 2) (1 4) (1 6) (2 3) (2 5) (3 4) (5 6) (5 8) (6 7))

We see that 1+2, 1+4 and 1+6 are all prime, but 1+8 is not, so it’s excluded from the result.

Simple iteration in Clojure

Imperative programmers frequently complain that one of the things that makes functional languages hard to learn is their lack of loops. Clojure actually does provide quite a few methods for doing iteration. We’ll have a look at some of them here.

Suppose we want to print out a table of squares of certain numbers. In Clojure, we can provide these numbers in a list, as in ‘(1 3 5 8 19) (remember the quote at the start is needed to stop Clojure interpreting the list as a function). To an imperative programmer, the way to do this is to set up a loop over each element in the list, calculating the square of each number. How can we do the equivalent in Clojure?

We can use the doseq macro. The code is

(defn squares-table [numlist]
  (doseq [num numlist]
    (println (str "Square of " num " = " (* num num)))))

The function squares-table takes a list as an argument. The doseq macro takes two arguments. The first, num here, is undefined before doseq is run. It is assigned each element of numlist in turn, and for each element, the form or forms (you can put any number of forms after the argument list) are executed. In this case, we just print out a string giving the square of num.

We could call this function in the REPL with

(squares-table ‘(1 3 5 8 19))

and we get the result:

Square of 1 = 1
Square of 3 = 9
Square of 5 = 25
Square of 8 = 64
Square of 19 = 361
nil

The ‘nil’ at the end is just the return value of squares-table.

Another iteration macro is dotimes. A variant of our squares-calculating program looks like this:

(defn squares-times [maxnum]
  (dotimes [num maxnum]
    (println (str "Square of " num " = " (* num num)))))

This time, squares-times takes a single argument, maxnum, not a list. The dotimes macro takes two arguments. The first, num here, is undefined at the start. It takes on each integer value from 0 up to maxnum – 1. For each value of num, the body of the dotimes is run, so in this case, we’ll get a table of squares from 0 up to maxnum – 1. Incidentally, maxnum can also be a character, in which case it is interpreted as that character’s ASCII code. So if we made the call (square-times \A), we’d get a table of squares from 0 up to 64, since ‘A’ has ASCII code 65. The backslash before the A is needed, since otherwise, Clojure will interpret A as a symbol, not a bare character.

Although the doseq and dotimes macros look quite powerful, they have one limitation which results in them not being used as much as you might think. The problem is that they both return only ‘nil’, so they don’t produce any data that can be used in subsequent functions. You might think that this is no big deal, since a ‘for’ loop in an imperative language doesn’t return anything either, but you can, of course define other data structures such as arrays that are constructed within a ‘for’ loop and are then used in subsequent code.

Clojure provides several other macros and functions that do return useful data, usually in the form of a list, and these macros are used much more than doseq and dotimes. One powerful function is map.

In its simplest form, map takes two arguments. The first is a unary function (that is, a function that takes a single argument), and the second is a list. map iterates through the list and applies the function to each item in the list in turn. The results are returned as a new list.

For example, suppose we wanted to create a list of all the squares of numbers within a given range. The following code does this.

(defn square [num]
  (* num num))

(defn squares-map [minnum maxnum]
  (map square (range minnum (inc maxnum))))

First, we define a simple unary function square which squares its argument. Then we define squares-map which takes two arguments. Then we call map to create the list of squares. The first argument to map is our square function that we’ve just defined. The second argument must be a list. We’ve used the range function (part of Clojure). When given two integer arguments, range returns a list starting with the first argument and ending with one less than the last argument. Since we want the final value maxnum to be included in our answer, we apply the inc function to add 1 to maxnum before sending it to range.

map will thus apply square to each number from minnum to maxnum and return the result as a list. For example, if we call (squares-map 3 9) we get back (9 16 25 36 49 64 81). Clearly the Clojure code for doing this is a lot shorter than in, say, Java. (OK, so a lot of work is being done for you by the people who wrote map and range and so on, but these functions are part of the Clojure language, rather than being optional add-ons, so you can rely on any installation of Clojure having them.)

Note, by the way, that this example shows a function square being passed as a parameter to another function map. This shows that functions are just data that can be passed around like any other kind of data; this is something that many imperative languages don’t let you do.

map is actually a lot more powerful than this simple example showed. In its more general form, it takes a function that takes any number of arguments, followed by the same number of lists of data. It will then pick off the first element from each list and pass these as arguments to the function, then it will pick out the second element from each list and pass those as arguments, and so on until it comes to the end of the shortest list, at which point it will stop and ignore all remaining data in other lists.

For example, suppose we had two lists of numbers and wanted to calculate a number that is the square of an element in the first list added to the square of the corresponding number in the second list. We can do this as follows.

(defn sum-squares [x y]
  (+ (square x) (square y)))

(defn add-squares [nums1 nums2]
  (map sum-squares nums1 nums2))

We first define a function sum-squares that takes two arguments and returns the sum of their squares (using the square function from earlier). Then we define add-squares that takes two lists, num1 and num2. We call map, giving it the sum-squares function and the two lists. For example, if we called (add-squares ‘(1 3 5 7) ‘(2 4 6)) we get back (5 25 61). This is because 1*1 + 2*2 = 5, 3*3 + 4*4 = 25 and 5*5 + 6*6 = 61. The final 7 in the first list is ignored since there is nothing in the second list to match it with.

Finally, we’ll have a look at the filter function. filter iterates through a list and tests each list element against a predicate function (a function that returns true or false). If an element is ‘true’ according to the predicate, it is included in a new list, otherwise it is excluded. The return from filter is a list of all elements from the original list that pass the predicate test.

For example, suppose we wanted a list of all the odd squares within a given range. We could do that using filter as follows.

(defn is-odd? [num]
  (= (rem num 2) 1))

(defn odd-squares [minnum maxnum]
  (let [numlist (range minnum (inc maxnum))
        squares (map square numlist)]
    (filter is-odd? squares)))

Our predicate function is-odd? tests if a single number is odd by calculating its remainder when divided by 2. The odd-squares function uses the map from our earlier function to calculate the list of squares within a given range, and then filter is applied to this list. We’ve used a let to make the code more readable. We could have written the whole thing on one line like this:

(defn is-odd? [num]
  (= (rem num 2) 1))

(defn odd-squares [minnum maxnum]
  (filter is-odd? (map square (range minnum (inc maxnum)))))

However, deciphering this code requires a fair bit of backwards thinking, so it’s not very human-readable. (Actually, we could have included the definition of is-odd? within that single line as well, as an anonymous function, but more on that when we consider ways of creating functions.)

Testing this function, we call (odd-squares 3 16) and get back (9 25 49 81 121 169 225).

Hopefully these little examples have illustrated the power and brevity of a lot of Clojure code.

Keyboard events in WPF

A keyboard event is generated whenever the user presses a key or a combination of keys on the keyboard. In order to direct a keyboard event to a particular element in the interface, that element must have the focus. As such, by default, only interface elements that can take the focus can receive keyboard events, so geometric shapes such as Rectangle and Ellipse, and layouts such as the Canvas do not take the focus (although they can be made to; see later).

The main keyboard events that we wish to handle are KeyUp and KeyDown. The easiest way to see how this is done is by considering an example. We’ll write a little program that displays a blank Canvas and allows the user to add little coloured squares to the Canvas by pressing certain keys. To begin, we’ll draw a filled square in either red, green or blue depending on whether the R, G or B key is pressed. All other keys do nothing.

Create a new WPF project in Visual Studio (you can use Expression Blend if you like, but we’ll be doing all the coding in VS). Change the default LayoutRoot to a Canvas (it’s created in VS as a Grid), and call it CanvasRoot. Add a handler for the KeyDown event to the Canvas, calling it CanvasRoot_KeyDown.

You’ll note that the second argument in this handler is an object of class KeyEventArgs. This object contains all the information you need to know about which key was pressed. In particular, the key can be found from the Key property, so we can set the colour of the square to be drawn like this:

      switch (e.Key)
      {
        case Key.R:
          squareColor = Colors.Red;
          break;
        case Key.G:
          squareColor = Colors.Green;
          break;
        case Key.B:
          squareColor = Colors.Blue;
          break;
        default:
          return;
      }

Each key has its own entry in the Key enum, and we’ve used the Colors enum to specify the colours by name, although we could also have used RGB values.

We can write the first version of a drawSquare() method that draws a square at a random position on the Canvas. We have:

    Random ranNum = new Random();
    int squareSize = 10;

    private void drawSquare(Color squareColor)
    {
      Rectangle square = new Rectangle();
      square.Fill = new SolidColorBrush(squareColor);
      square.Width = squareSize;
      square.Height = squareSize;
      int squareX = ranNum.Next((int)CanvasRoot.ActualWidth - squareSize);
      int squareY = ranNum.Next((int)CanvasRoot.ActualHeight - squareSize);
      Canvas.SetLeft(square, squareX);
      Canvas.SetTop(square, squareY);
      CanvasRoot.Children.Add(square);
    }

We’ve created a Random object on line 1 so we can generate random numbers. We’ve set the square size to 10 on line 2.

The rest of the method should be fairly self-explanatory, but note that in order to ensure that the entire square is drawn within the boundaries of the Canvas, we use the ActualWidth and ActualHeight values of the Canvas, since the Width and Height properties are not defined as numbers if the Canvas’s dimensions are set to ‘Auto’. We subtract off the squareSize to ensure the square fits inside the Canvas. The last three lines of the method set the square’s position and add it as a child of the Canvas.

If you run the program as it is, you’ll probably find that pressing R, G or B has no effect. This is because, as we mentioned above, the Canvas by default does not take the focus, so even clicking in it with the mouse won’t help. There are two solutions to this problem. Perhaps the simplest is to move the event handler from the Canvas to the underlying Window, and if you do that, you’ll find the program now works. However, this isn’t the best solution, since in a more general application, the Canvas might be just one component of a larger interface, and we want  the Canvas to have the focus only some of the time.

The other solution is to make the Canvas focusable and give it the focus. This is easily done by adding a couple of lines to the MainWindow() constructor:

    public MainWindow()
    {
      InitializeComponent();
      CanvasRoot.Focusable = true;
      CanvasRoot.Focus();
    }

The only drawback to this is that the Canvas now has a dotted line drawn around it. There are ways to fix this too, but we’ll leave it for now.

That’s about all there is to keyboard events if all you want to do is detect when a single key has been pressed or released. However, often we want to press a modifier key such as Shift or Control to give a different effect. We’ll illustrate this here by modifying the program so that if the Shift key is pressed along with R, G or B, the square is drawn in outline rather than filled. Furthermore, if we press the Shift and Control keys together, we get a filled magenta square no matter which of R, G or B is pressed. To implement this, we can add the following to the CanvasRoot_KeyDown handler:

      squareStyle style;
      if (Keyboard.Modifiers == ModifierKeys.Shift)
      {
        style = squareStyle.Outline;
      }
      else if (Keyboard.Modifiers == (ModifierKeys.Shift | ModifierKeys.Control))
      {
        squareColor = Colors.Magenta;
        style = squareStyle.Fill;
      }
      else
      {
        style = squareStyle.Fill;
      }

We’ve added an enum definition at the top of the class to handle the different styles of square:

    enum squareStyle { Fill, Outline };

If we have only a single modifier key, we can test for this using a simple == comparison as on line 2. The Keyboard.Modifiers value contains a code giving all modifier keys that have been pressed, where each bit in the code corresponds to a different modifier. If a particular modifier such as Shift has been pressed, its corresonding bit will be 1 with all other bits set to 0.

If we have more than one modifier pressed, such as Shift + Control, then both their bits will be 1, so we can compare Keyboard.Modifiers to the bitwise-or of ModifierKeys.Shift and ModifierKeys.Control.

We now modify the drawSquare() method to cope with different styles as well as colours:

    private void drawSquare(Color squareColor, squareStyle style)
    {
      Rectangle square = new Rectangle();
      switch (style)
      {
        case squareStyle.Outline:
          square.Stroke = new SolidColorBrush(squareColor);
          break;
        default:
          square.Fill = new SolidColorBrush(squareColor);
          break;
      }
      square.Width = squareSize;
      square.Height = squareSize;
      int squareX = ranNum.Next((int)CanvasRoot.ActualWidth - squareSize);
      int squareY = ranNum.Next((int)CanvasRoot.ActualHeight - squareSize);
      Canvas.SetLeft(square, squareX);
      Canvas.SetTop(square, squareY);
      CanvasRoot.Children.Add(square);
    }

We see that we set Stroke for outlines and Fill for fills.

There is one fly in the ointment however. The Alt modifer behaves in a strange way and must be handled separately. If Alt is combined with another modifier, as in Shift+Alt, then it can be handled in the same way as above. However, if you try to use Alt on its own as a modifer, the above code won’t work. This is because, in Windows, Alt is used as a System key in such operations as Alt+Tab for switching between windows. If Alt is pressed when you press any other key, the e.Key field will always come up as Key.System. In order to access the underlying key that was pressed along with Alt, you need to access the SystemKey field of the KeyEventArgs object. For example, if we want to have Alt+Y produce a yellow (goldenrod, actually) filled square, we could write within the key down handler:

      if ((Keyboard.Modifiers == ModifierKeys.Alt) && (e.SystemKey == Key.Y))
      {
        squareColor = Colors.Goldenrod;
        drawSquare(squareColor, squareStyle.Fill);
        return;
      }

With this final addition, the complete handler looks like this:

    private void CanvasRoot_KeyDown(object sender, KeyEventArgs e)
    {
      Color squareColor;

      // Alt key is treated differently. e.Key == System when Alt is pressed;
      // Actual key is stored in e.SystemKey
      if ((Keyboard.Modifiers == ModifierKeys.Alt) && (e.SystemKey == Key.Y))
      {
        squareColor = Colors.Goldenrod;
        drawSquare(squareColor, squareStyle.Fill);
        return;
      }

      switch (e.Key)
      {
        case Key.R:
          squareColor = Colors.Red;
          break;
        case Key.G:
          squareColor = Colors.Green;
          break;
        case Key.B:
          squareColor = Colors.Blue;
          break;
        default:
          return;
      }

      squareStyle style;
      if (Keyboard.Modifiers == ModifierKeys.Shift)
      {
        style = squareStyle.Outline;
      }
      else if (Keyboard.Modifiers == (ModifierKeys.Shift | ModifierKeys.Control))
      {
        squareColor = Colors.Magenta;
        style = squareStyle.Fill;
      }
      else
      {
        style = squareStyle.Fill;
      }

      drawSquare(squareColor, style);
    }

The complete code for this post is available here.