Category Archives: WPF

Hyperlink columns: displaying the link in a browser

A while back I posted an article on how to use the WPF DataGridHyperlinkColumn. There, the web page referenced by the hyperlink was displayed in the application’s own window, using WPF’s internal web browser. This browser has a lot of limitations, and it’s more usual for links like these to lead to the page being displayed in the user’s favourite web browser.

This post shows the modifications we need to make to have this happen.

The first thing we need to do (assuming we don’t want the page to show up in the application’s own window as well) is convert all uses of the NavigationWindow back to a normal Window. This is fairly safe to do by using a global find and replace in Visual Studio. Typically, NavigationWindow is used only in the XAML file and in the behind code for this file (where it serves as the base class for the MainWindow class). This will prevent the web page from appearing in the application itself.

To get the link to show up in the default browser, we need to add an explicit event handler to the DataGridHyperlinkColumn. If we modify the hyperlink column we used in our earlier example of a comic book database application, the XAML now looks like this:

                                <DataGridHyperlinkColumn  Header="ComicVine" Binding="{Binding ComicVine}"
                                        ContentBinding="{Binding ComicVine, Converter={StaticResource ComicVineConverter}}"
                                          Width="67">
                                    <DataGridHyperlinkColumn.ElementStyle>
                                        <Style>
                                            <EventSetter Event="Hyperlink.Click" Handler="WebPageClick"/>
                                        </Style>
                                    </DataGridHyperlinkColumn.ElementStyle>
                                </DataGridHyperlinkColumn>

The properties of the hyperlink column itself are the same as before. The change is that we’ve added an ElementStyle section, in which we’ve provided a link to a handler for the Hyperlink.Click event. This handler is in the MainWindow class and looks like this:

    private void WebPageClick(object sender, RoutedEventArgs e)
    {
      Hyperlink link = e.OriginalSource as Hyperlink;
      Process.Start(link.NavigateUri.AbsoluteUri);
    }

This code retrieves the hyperlink that was clicked, and then starts an external process by calling Process.Start() with the hyperlink as the argument. This uses Windows’ association of file type to application, so if your default browser is, say, Google Chrome, then sending a URI to Process.Start() will cause Chrome to be started and sent the URI to display.

In order for this code to work, you’ll need a couple of ‘using’ statements at the top:

using System.Diagnostics;
using System.Windows.Documents;

That’s all there is to it.

Advertisements

WPF Context Menus

context menu is a menu that pops up at some point on your interface when you click the right mouse button. It’s not attached to the menu bar at the top. As an example, we’ll examine the code we used for the printing demo in the last post, and in the process add a feature to it that illustrates some of the properties of context menus.

A quick reminder of what this application does. It displays an A4-sized Canvas on which the user could add TextBoxes by right-clicking with the mouse and selecting ‘Add TextBox’ from the popup menu. It also allows you to add multiple pages and print them, but we dealt with that aspect in the last post.

The popup menu on the Canvas is a simple example of a context menu. We can add the menu by inserting a bit of XAML code:

        <Canvas Name="pageCanvas" Margin="0" HorizontalAlignment="Center" VerticalAlignment="Center"
                Height="1122.51968503937" Width="793.700787401575" Background="White" MouseRightButtonDown="pageCanvas_MouseRightButtonDown">
            <Canvas.ContextMenu>
                <ContextMenu Name="pageCanvasContextMenu">
                    <MenuItem x:Name="addTextBoxMenuItem"  Header="Add TextBox" Click="addTextBoxMenuItem_Click"/>
                </ContextMenu>
            </Canvas.ContextMenu>
        </Canvas>

Here we define the context menu in the Canvas.ContextMenu section. The MenuItems that are added to a context menu are the same as those added to a Menu in a fixed menu bar, so there’s no mystery here. The Header is the text that appears on the MenuItem, and we add an event handler for clicking on the MenuItem in the usual way.

One thing is worthy of note however. Annoyingly, the RoutedEventArgs parameter that is passed to the event handler doesn’t contain the position of the mouse when the menu was clicked, so we need to get that another way. What I’ve done here is add a MouseRightButtonDown event handler to the Canvas itself. We extract the mouse coordinates in that event handler and save them for use in the handler for the context menu, since we want to add the TextBox at the mouse location. The code for MouseRightButtonDown is:

    double rightX, rightY;
    private void pageCanvas_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
      rightX = e.GetPosition(pageCanvas).X;
      rightY = e.GetPosition(pageCanvas).Y;
    }

Now we can write the code for inserting the TextBox:

    private void addTextBoxMenuItem_Click(object sender, RoutedEventArgs e)
    {
      document.AddTextArea(RightX, RightY);
      DrawPage();
    }

The program defines a Document object which contains a list of TextAreas, as mentioned in the previous post. Each TextArea contains some text and the coordinates where the corresponding TextBox should be drawn. The link between TextArea (a non-graphical class) and TextBox (the WPF Control) is done via styles and data binding, but we won’t go into the details here, since we want to concentrate on the context menu. If you want the full code, you can download it via the link at the end.

That’s how you add a context menu to an object (such as a Canvas) that doesn’t have one by default. However, suppose you want to add a context menu to the TextBox itself. For example, the text you enter into the TextBox might make frequent use of some Unicode characters that aren’t available on your keyboard. It’s a pain to have to find these characters somewhere else (for example, in the ‘charmap’ application that comes with Windows) and copy and paste them into your program. In this example, we’ll add context menu items to the TextBox that allow the fractions ½ and ¼ to be added to the TextBox.

There’s one problem that confronts us, though. If you right-click on a standard TextBox, you’ll see that it already has a context menu containing the cut, copy and paste commands. How do we add our custom commands to the existing ones (or replace the existing ones)?

We need to define the custom context menu as a Window resource, so in the XAML we can write:

    <Window.Resources>
        <ContextMenu x:Key="TextBoxContextMenu" Background="White">
            <MenuItem Command="ApplicationCommands.Copy" />
            <MenuItem Command="ApplicationCommands.Cut" />
            <MenuItem Command="ApplicationCommands.Paste" />
            <MenuItem x:Name="insertHalfMenuItem" Header="Insert ½" Click="insertHalfMenuItem_Click"/>
            <MenuItem x:Name="insertQuarterMenuItem" Header="Insert ¼" Click="insertQuarterMenuItem_Click"/>
        </ContextMenu>
        <Style x:Key="TextBoxStyle" TargetType="TextBox">
            <Setter Property="AcceptsReturn" Value="True"/>
            <Setter Property="TextWrapping" Value="WrapWithOverflow"/>
            <Setter Property="BorderBrush" Value="RosyBrown"/>
            <Setter Property="FontSize" Value="12"/>
            <Setter Property="FontWeight" Value="Normal"/>
            <Setter Property="Text" Value="{Binding Content}" />
            <Setter Property="Height" Value="200"/>
            <Setter Property="Width" Value="150"/>
            <Setter Property="ContextMenu" Value="{StaticResource TextBoxContextMenu}"/>
        </Style>
    </Window.Resources>

We’ve given the complete resources used in this program. The top bit defines the ContextMenu, in which we’ve retained the three default commands and added two extra ones to allow us to insert fractions into the text.

In the Style, we set up the visual properties of the TextBox, and at the end, we define its ContextMenu property as the ContextMenu we’ve just created. When we create the TextBox in code, we assign its Style to be TextBoxStyle, which will attach the desired ContextMenu to it. This is done in the DrawPage() method in the MainWindow class:

    public void DrawPage(Canvas canvas)
    {
      canvas.Children.Clear();
      Page page = document.CurrentPage;
      foreach (TextArea textArea in page.TextBoxList)
      {
        TextBox textBox = new TextBox();
        textBox.Style = (Style)FindResource("TextBoxStyle");
        textBox.DataContext = textArea;
        Canvas.SetLeft(textBox, textArea.X);
        Canvas.SetTop(textBox, textArea.Y);
        canvas.Children.Add(textBox);
      }
    }

The TextBox is created and has its Style set. Its position on the Canvas uses the coordinates we got from the MouseRightButtonDown event handler earlier.

One final problem remains to be solved. As you’ve seen above, it is the TextArea objects that are stored in the Document, and the TextBoxes are created on the fly whenever we want to draw a page. How can we get hold of the TextBox in order to add some text to it in response to a context menu click? The TextBox doesn’t have an object name that is accessible outside the DrawPage() method, so it seems we’re a bit stuck.

If we examine the code for the context menu’s event handlers, we can see how to do it.

    private void insertHalfMenuItem_Click(object sender, RoutedEventArgs e)
    {
      addStringToTextBox(sender, "½");
    }

    private void insertQuarterMenuItem_Click(object sender, RoutedEventArgs e)
    {
      addStringToTextBox(sender, "¼");
    }

    private void addStringToTextBox(object sender, string text)
    {
      MenuItem contextMenuItem = (MenuItem)sender;
      TextBox stampBox = ((ContextMenu)contextMenuItem.Parent).PlacementTarget as TextBox;
      int caretIndex = stampBox.CaretIndex;
      stampBox.Text = stampBox.Text.Insert(stampBox.CaretIndex, text);
      stampBox.CaretIndex = caretIndex + 1;
    }

The sender of the context menu event is the MenuItem that was clicked. The Parent of this MenuItem is the ContextMenu object itself, and its PlacementTarget is the UIElement that owns it. So by this roundabout route we can get the TextBox over which the mouse was right-clicked to produce the ContextMenu. The last bit of code makes sure the fraction is inserted at the correct location in the TextBox’s text by retrieving the CaretIndex. After the text has been inserted we position the CaretIndex just after it so the user can carry on typing in the usual way.

Get source code here.

Printing in WPF

Writing code for printing has a bad reputation. WPF’s support for is a bit sketchy, but a basic task like printing out a multipage document actually isn’t that hard, once you know what to do. It turns out the ‘knowing what to do’ bit isn’t that easy, since it took a lot of googling and just plain experimentation to finally get it to work.

In this post I’ll describe a demo application that allows the user to create a number of separate pages, and then to add TextBoxes to each page. Text can be typed into each TextBox, and then the whole set of pages can be sent to the printer.

Although there is a complicated way of producing printout using classes from Microsoft’s XPS (XML Paper Specification) library, you don’t actually need to use this method. The technique I’ll cover here is considerably simpler.

First, I’ll describe the demo application. It consists of a simple interface, with an A4-sized Canvas on the left (for non-European readers, A4 is the standard paper size in the UK, and is 210 mm x 297 mm, or roughly 8.3 x 11.7 inches). On the right are a control that lets you nagivate between pages, and button that inserts a new page at the current location, and a button that opens up the print dialog. You can right-click on the Canvas to insert a TextBox at the mouse point, and then type text into the TextBox. Although there are a few interesting techniques used in the program that deal with various non-printing tasks, I won’t cover them here since I want to concentrate on the printing. (You can download a working project using the link at the bottom of this post.)

In order to print a multipage document, you need to write your own version of the DocumentPaginator class (in the System.Windows.Documents namespace). This is an abstract class that contains several methods and properties that you’ll need to override and fill in to produce printed output. Your overridden DocumentPaginator’s main purpose is to provide the graphics required for each page that is to be printed. The technique I’ll use here involves creating a Canvas onto which you do all your drawing, and then returning a DocumentPage (another class in System.Windows.Documents) that is created from the Canvas. So, without further ado, here’s my version of a DocumentPaginator:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;

namespace PrintingDemo
{
  class Paginator : DocumentPaginator
  {
    Document document;
    Canvas pageCanvas;
    public Paginator()
    {
      MainWindow mainWindow = (MainWindow)Application.Current.MainWindow;
      document = mainWindow.Document;
      pageCanvas = mainWindow.PageCanvas;
    }

    public override DocumentPage GetPage(int pageNumber)
    {
      Canvas printCanvas = new Canvas();
      MainWindow mainWindow = (MainWindow)Application.Current.MainWindow;
      mainWindow.Document.CurrentPageIndex = pageNumber;
      mainWindow.DrawPage(printCanvas);
      printCanvas.Measure(PageSize);
      printCanvas.Arrange(new Rect(new Point(), PageSize));
      printCanvas.UpdateLayout();
      return new DocumentPage(printCanvas);
    }

    public override bool IsPageCountValid
    {
      get { return true; }
    }

    public override int PageCount
    {
      get { return document.PageCount; }
    }

    public override System.Windows.Size PageSize
    {
      get
      {
        return new Size(pageCanvas.Width, pageCanvas.Height);
      }
      set
      {
        throw new NotImplementedException();
      }
    }

    public override IDocumentPaginatorSource Source
    {
      get { return null; }
    }
  }
}

All the methods and properties (except the constructor) are overrides of the corresponding parts of the abstract DocumentPaginator base class. I don’t claim to be an expert here, so I’m not 100% certain what all of them are used for, but some of them should be fairly obvious.

First, I’ve added a couple of local objects to the Paginator class. The Document class is the one that stores the list of pages created by the user (that is, Document is a class I wrote for this demo; it’s not part of the printing code). The Canvas is the usual WPF control, and pageCanvas is the Canvas on which the TextBoxes are drawn by the user on screen. It’s needed here, since we want the dimensions of the printed output to be the same as those of the on-screen Canvas, which is set up to be A4-sized. Since the Canvas is declared in the MainWindow class (it’s actually declared in the XAML, but that’s irrelevant here really), we need to access it. I suppose this isn’t exactly the best class design, but I’m trying to get to printing as quickly as possible, so it’ll do. In any case, the Paginator constructor simply accesses the MainWindow to get these two objects.

Now we can have a look at the overridden methods and properties. We’ll look at the properties first, since the GetPage() method is the meat of the class and is where most of the work is done, so we’ll get the easy stuff out of the way first.

If (as in this demo) you know the number of pages in your document, you can just return this as the PageCount property. In this demo, the Document class contains a property called PageCount which gives the number of pages stored in it, so we can just return that. In more complex cases, such as a long text document, you may have to work out the number of pages by calculating how much text you can put on each page, allowing for headers, footers, margins and so forth. That could be an onerous task, so we won’t look into it here.

The PageSize property is just what it says, and again we just return the size of the Canvas used for on-screen drawing. If you want to specify this size from scratch, remember that graphics in WPF uses the device-independent pixel as its basic unit, and one pixel is exactly 1/96th of an inch. As an example, the A4 canvas comes out to a size of 210 mm = 793.7 pixels wide and 297 mm = 1122.5 pixels high. The ‘set’ part of this property is required in the override, but again it seems never to be called so I haven’t implemented it.

I have to be honest and say that I don’t really know what the IsPageCountValid and Source properties do, but for this simple example, returning ‘true’ for the former and ‘null’ for the latter seems to work well, so we’ll not try to fix something that seems not to be broken.

Finally, we consider the GetPage() method. This method takes a zero-based page number as its argument, and its responsibility is to generate a DocumentPage that contains the graphics that is to be printed for that page number. Obviously the code you put in here depends on what you’re trying to print, but there are a few things you always need to do, no matter what your graphics are.

The approach I’ve taken here is to create a local Canvas on which the current page will be drawn. Since the on-screen interface of the program shows only one page at a time, there is a DrawPage() method in MainWindow that draws the current page using the data stored in the Document object. Document doesn’t store any actual graphical controls; rather it stores a list of data objects that specify what text is to be placed in each TextBox, and where the TextBox should be drawn. The code is this:

    public void DrawPage(Canvas canvas)
    {
      canvas.Children.Clear();
      Page page = document.CurrentPage;
      foreach (TextArea textArea in page.TextBoxList)
      {
        TextBox textBox = new TextBox();
        textBox.Style = (Style)FindResource("TextBoxStyle");
        textBox.DataContext = textArea;
        Canvas.SetLeft(textBox, textArea.X);
        Canvas.SetTop(textBox, textArea.Y);
        canvas.Children.Add(textBox);
      }
    }

The same Canvas is used to draw each page, so its Children collection is first cleared to make room for the new page about to be drawn. We then retrieve the current Page from the Document (again, Page is a class I wrote for this demo). The Page class contains a list of TextArea (another class I wrote, which stores the text and location for each TextBox) objects. For each TextArea, we create a TextBox. I’ve defined a WPF Style in the XAML, and used data binding to connect the Text property of the TextBox to the text stored in the TextArea object. Again, all this stuff is peripheral to the printing, but see the source code if you’re interested in the details.

Each TextBox is then positioned on the Canvas and added as a child of that Canvas. It is this method that is used to produce the graphical representation of the data stored in a Page object, and it is worth noting that it is the same code that is used to produce both the on-screen graphics and the graphics that are sent to the printer. This means that WYSIWYG is pretty well guaranteed.

Back in the GetPage() method in the Paginator code, you’ll notice four lines after the call to DrawPage(). These lines are the essential bit for all GetPage() methods. You’ll need to call Measure() first, and pass it the size of the Canvas. Then you’ll need to call Arrange(), and pass it a Rect whose arguments are an upper left coordinate of (0,0) (which is produced by a Point object by default), and again the Canvas size. Finally, you need to call UpdateLayout(). If you leave out the calls to Measure() and Arrange(), the TextBoxes won’t appear at all; if you omit UpdateLayout(), the TextBoxes will appear, but the text inside them won’t.

Finally, you create a DocumentPage object and pass it the Canvas. This completes the creation of the graphics for the printout.

OK, so how you do the actual printing? If all you want to do is print out all the pages in the document, this is quite easy. If you want to specify a range of pages from within the document, this is a bit trickier and we’ll get to that later.

To print all the pages, we’ll look at the code in the event handler for the Print button:

    private void printButton_Click(object sender, RoutedEventArgs e)
    {
      PrintDialog printDialog = new PrintDialog();
      if (printDialog.ShowDialog() == true)
      {
        DocumentPaginator paginator = new Paginator();
        printDialog.PrintDocument(paginator, "Print demo");
      }
    }

We create and display a PrintDialog. If the user presses ‘Print’ in the dialog, the dialog returns ‘true’, and we then simply create a Paginator object and pass it to the PrintDialog’s PrintDocument() method. And that’s it.

One final note. If you’re worried about wasting reams of paper testing your printing code, you should be able to see the results on-screen without having to actually print anything. If you’ve installed .NET (which you have to do to use Visual Studio anyway), you should notice the Microsoft XPS Document Writer as one of the available printers in the PrintDialog. If you select that, your output will be saved to an XPS file, which you can then look at with the XPS Viewer (again, this should have been installed when you installed Visual Studio) which should open if you double-click on the XPS file. Another possibility, if you have Office 2010 installed, is that OneNote allows you to send printer output to it, so again you can see it without wasting any paper. Some other programs may have readers for printer output, so check what shows up in your printer list in the PrintDialog.

Get the source code here.

DataGridTemplateColumn for the WPF DataGrid

We’ve been looking at using the WPF DataGrid with its ItemsSource bound to data from a MySQL database (see the WPF index for a list of articles). One of the built-in DataGrid column types is the DataGridComboBoxColumn, which allows you to bind a list of items to a ComboBox that is displayed whenever the user wishes to edit the cell. When the cell is not being edited, the selected item from the ComboBox is displayed as an ordinary TextBlock.

This feature would be nice in a more general way. For example, a common field in a database is a date, so it would be nice if a DataGrid cell could display a date as text, but switch to a DatePicker control when the user wishes to edit the date. The DataGridTemplateColumn provides just this sort of feature.

Let’s look at how we could implement the date display/edit column. Going back to our comic book database, suppose we wished to store the date that we last read a particular issue. We insert a DateRead column in the MySQL database. This column has the MySQL data type of ‘date’. As before, we load the data from the ‘issues’ table into a WPF DataTable and use data binding to select which column from the DataTable is displayed in each column of the DataGrid. In the case of a template column, however, we need to specify the two types of cell (displaying and editing) separately. The XAML looks like this:

                <DataGridTemplateColumn Header="Date read">
                  <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                      <TextBlock Text="{Binding DateRead, Converter={StaticResource DateConverter}}" HorizontalAlignment="Center"/>
                    </DataTemplate>
                  </DataGridTemplateColumn.CellTemplate>
                  <DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                      <DatePicker SelectedDate="{Binding DateRead}" />
                    </DataTemplate>
                  </DataGridTemplateColumn.CellEditingTemplate>
                </DataGridTemplateColumn>

The CellTemplate part specifies what each cell displays when it’s not being edited. In this case we insert a TextBlock which is bound to the DateRead field. (We’ll look at the converter in a minute.) This means that the value of DateRead is displayed and since it’s a TextBlock (as opposed to a TextBox), there’s no way to edit it, which is fine.

The CellEditingTemplate shows what is displayed when the user double-clicks on the cell in order to edit its contents. In this case we display a DatePicker, which is a control with a small text area and a calendar icon which, when clicked, displays a calendar month. Clicking on the header of a DatePicker allows the user to choose another month or year, and a particular date is selected by clicking on the date’s day number. The selected date is then displayed in the text area. When the cell loses focus (when the user clicks somewhere else), the cell goes back to its TextBlock incarnation. The binding on the DatePicker ensures that the selected date is transmitted back to the DataTable.

That’s really all there is to using a template column. Remember that you can put any layout you like inside a DataTemplate, so if you wanted to get fancy you could even put in a Grid and then enclose multiple controls inside the Grid. Although the power is there, of course, putting in too much clutter makes for a bad user interface, so usually template columns use only one or two controls as we’ve done here with the DatePicker.

One final note concerning dates. Although we’re using a ‘date’ data type and not a ‘datetime’ type, for some reason, dates always seem to come attached to a time as well (usually 00:00:00), and unless we do something about it, the date and time get displayed in the TextBlock. This sort of thing is easy to fix using a converter for a data binding. We’ve seen data converters before, so this one doesn’t really introduce anything new. The idea is that we strip off the time portion of the date and return just the date portion. The C# code is:


  class DateConverter : IValueConverter
  {
    // Strip off the time part of the dateTime
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      if (value != null && value.ToString().Length > 0)
      {
        string dateTime = value.ToString();
        int space = dateTime.IndexOf(" ");
        string date = dateTime.Substring(0, space);
        return date;
      }
      string empty = "";
      return empty;
    }

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

We search for the blank that separates the date from the time and then use Substring() to get the date part of the string. The ConvertBack() bit should never be used.

Hyperlink columns in a WPF DataGrid

In the last couple of posts (here and here) we’ve seen how to connect to a MySQL database and use a DataGrid as a UI for editing the contents of the database. One useful feature of a DataGrid is its DataGridHyperlinkColumn, in which each cell is a hyperlink to a URL. In the Comics database, for example, we store with each comic a link to its page at the ComicVine web site.

In order for the hyperlinks in such a column to become active, we need to embed the page in a NavigationWindow or a Frame. We’ll have a look at NavigationWindow here.

The NavigationWindow works pretty much the same way as the ordinary Window. To convert an existing Window-based WPF application into one using NavigationWindow, replace the Window tag at the start and end by NavigationWindow. Also, change the Window.Resources block to NavigationWindow.Resources.

One difference, however, is that the NavigationWindow doesn’t support direct content, meaning that you can’t place a layout manager like Grid directly into a NavigationWindow. After the NavigationWindow.Resources block, you need to insert a NavigationWindow.Content block, and you can then place your root Grid layout inside that. Those are the only changes you need to make to convert to NavigationWindow.

So what does a NavigationWindow do for you? The main thing is that it provides an embedded web browser, so that when you click on a hyperlink, the web page will be displayed inside the application’s main window. You will also see ‘forward’ and ‘back’ navigation buttons at the top of the window, which work in the same way as in a regular browser, except that the original display of the DataGrid is included in the sequence of windows displayed. For example, if you start with a DataGrid containing a hyperlink and click on the hyperlink, you’ll be sent to the web page you clicked on. If you then click the ‘back’ button, you’re taken back to the DataGrid.

I haven’t explored the browser in great depth, but it appears to be a stripped-down version of Internet Explorer. It seems to be OK for displaying more web pages, but pages requiring interaction (such as the editing page at ComicVine) aren’t fully supported; the text editor on this page won’t work, and ComicVine provides a simpler notepad-like editor in its place. But for just displaying a page for the user’s information it seems fine.

One other feature of the hyperlink column is worth mentioning. By default, the column will display the text entered into a cell as a hyperlink. However, usually URLs are quite long and often don’t contain user-friendly text so it’s not obvious where the link is directing you. A better interface can be built by providing a converter that displays more user-friendly text. In the Comics example, the entry for the column is this:

   <DataGridHyperlinkColumn  Header="ComicVine" Binding="{Binding ComicVine}"
     ContentBinding="{Binding ComicVine, Converter={StaticResource ComicVineConverter}}"
     IsReadOnly="True"/>

The ‘Binding’ property binds the text that is used as the URL. By default, this is also the text that is displayed in the column’s cells. If we want the column to display different text, but still link that text to the underlying URL, we can specify a ‘ContentBinding’. In this case, we’ve bound the content to the same text as the main URL binding, but we’ve provided a converter which will change the text displayed. In a cleverer application, we might be able to extract some text from the URL to create a user-friendly label. In this case, however, we’ve just produced the constant string ‘ComicVine’ as the display content. The converter is specified in the NavigationWindow.Resources section as:

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

The code behind looks like this:

  class ComicVineConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      if (value != null && value.ToString().Length > 0)
      {
        string comicVine = "ComicVine";
        return comicVine;
      }
      string empty = "";
      return empty;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      Uri comicVine = new Uri((string)value);
      return comicVine;
    }
  }

We could get fancy and do some string parsing on the URL, or we could pass in a parameter containing other information such as the issue’s title and number, and use these to build a label tailored to each issue. However, since all the information is already displayed on the same row in the DataGrid, this seems a bit redundant.

DataGrids in WPF

In the last post, we saw how to connect a MySQL database to a WPF application, and how to bind a ComboBox to the DataTable containing the data from the database. In most applications, however, we’d like to view more than one record from the database at a time, and for that, the DataGrid is the ideal control. In the last post, we showed the UI containing a DataGrid for displaying the issues of a particular title of comic book. Here we’ll have a look at how this is achieved.

The process is similar to that used for binding a ComboBox to a DataTable, but a DataGrid is more versatile so there are a few tricks we need to get it to work properly. First, we need to get the data from the MySQL database, and we use the same technique as in the previous post. We create an ObjectDataProvider in the XAML:

    <ObjectDataProvider x:Key="BooksTable"
    ObjectType="{x:Type local:DatabaseTable}"
    MethodName="GetTable">
      <ObjectDataProvider.MethodParameters>
        <s:String>SELECT * FROM issues</s:String>
        <s:String>IssueYear, IssueMonth, IssueDay</s:String>
      </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>

In this case, we load all the columns from the ‘issues’ table in the database. The second string passed to the GetTable() method shows how we sort the data in the DataTable: first by IssueYear, then by IssueMonth and finally by IssueDay.

Now we need to see how to define a DataGrid that is bound to the DataTable and displays the columns we want. We have:

      <TabControl>
        <TabItem Header="Books" Margin="0"  DataContext="{StaticResource BooksTable}">
<!-- Code setting up properties of TabItem... -->
            <DataGrid ItemsSource="{Binding Mode=OneWay}" AutoGenerateColumns="False" IsSynchronizedWithCurrentItem="True"
                    x:Name="booksDataGrid" Margin="0,0,0,0" d:LayoutOverrides="Height" Grid.Row="2" Grid.ColumnSpan="2" HorizontalAlignment="Center">
              <DataGrid.Columns>
                <DataGridTextColumn Header="Vol" Width="Auto" Binding="{Binding Volume}"/>
                <DataGridTextColumn Header="#" Width="Auto" Binding="{Binding Number}"/>
                <DataGridTextColumn Header="Day" Width="Auto" Binding="{Binding IssueDay}"/>
                <DataGridTextColumn Header="Month" Width="Auto" Binding="{Binding IssueMonth}"/>
                <DataGridTextColumn Header="Year" Binding="{Binding IssueYear}"/>
                <DataGridTextColumn Header="Title" Binding="{Binding IssueTitle}" MaxWidth="400" Width="400"/>
                <DataGridHyperlinkColumn  Header="ComicVine" Binding="{Binding ComicVine}"
                                        ContentBinding="{Binding ComicVine, Converter={StaticResource ComicVineConverter}}"/>
              </DataGrid.Columns>
            </DataGrid>
        </TabItem>
      </TabControl>

We’ve shown the enclosing TabControl and TabItem since we set the data context of the TabItem to be the BooksTable StaticResource we created above. This is the default data context for all controls within this particular TabItem, so when we bind the DataGrid on line 4, the binding is to BooksTable.

The default behaviour of a DataGrid is to automatically generate a column for each column in the DataTable that it is displaying. We don’t want this to happen here, since we don’t want Key_Issues (the primary key for the issues table)  to be displayed. We therefore set AutoGenerateColumns to False.

The IsSynchronizedWithCurrentItem property determines whether the currently selected row in the DataGrid is synchronized with the CurrentItem in the collection view of the data source. Remember that WPF automatically inserts a collection view between a data source and the control which is bound to that source. This collection view maintains a CurrentItem marker that points to the currently selected item, and we want that item also to be selected in the DataGrid.

The other properties in the DataGrid deal mostly with its appearance, so we can move along to looking at the DataGrid’s column definitions. There are several pre-defined types of column that we can use. This application uses three of them: the DataGridTextColumn, which displays a text box in each cell in the grid, a DataGridHyperlinkColumn, which displays text as a hyperlink, and a DataGridComboBoxColumn, where each cell appears as text unless it is selected, in which case it turns into a ComboBox containing a fixed list of items (the DataGridComboBoxColumn is used in another part of the program, so we won’t examine it here). It is also possible to create your own custom type of DataGrid column, but we won’t need that here. The Books DataGrid displays all its columns as text, except for the ComicVine column, which is displayed as a hyperlink so the user can open the ComicVine web page for that comic book issue.

Each of the DataGridTextColumns is bound to one of the columns in the DataTable that is the data context. (The ComicVine column has an extra ContentBinding that we’ll get to later.)

As it stands, when the program starts, the DataGrid displays all the issues in the database, sorted by their dates. This isn’t terribly useful, so we need to arrange things so that when the user selects a title from the ComboBox, the DataGrid displays only those issues from that title. To do this, we add an event handler to the booksTitlesComboBox (the ComboBox we dealt with in the last post) to handle the SelectionChanged event. It looks like this:

    bool changingTitle = false;  // Prevent row changed events when changing title
    private void booksTitlesComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      changingTitle = true;
      if (booksTitlesComboBox.SelectedValue != null)
      {
        DataTable booksTable = (DataTable)((DataSourceProvider)FindResource("BooksTable")).Data;
        int titleNumber = (int)booksTitlesComboBox.SelectedValue;
        databaseTable.GetTable("SELECT * FROM issues WHERE Title=" + titleNumber, booksTable);
      }
      changingTitle = false;
    }

The ‘changingTitle’ variable will be needed a bit later, so for now just ignore it. What we want to do is update the booksTable DataTable so that it contains only those issues corresponding to the currently selected title. We must first retrieve booksTable in the C# code, since it was defined in the XAML. This is done on line 7, where we used FindResource() to retrieve a resource with a given name. We need to cast this to a DataSourceProvider, and then extract its Data property, which we must then cast to a DataTable (complicated, but once we’ve done it, it’s the same format for retrieving any resource).

We then get the SelectedValue from booksTitleComboBox (remember that the SelectedValue is a Key_Titles value, not the textual Title; this is what we need for looking up issues based on their title).  On line 9, we construct a SQL query to select issues for that title. This uses a different version of the GetTable() method, which takes an existing DataTable and changes its contents. It looks like this:

    public void GetTable(String query, DataTable refreshDataTable)
    {
      refreshDataTable.Clear();
      String connString = "server=localhost;uid=root;pwd=xxxx;database=comics;";
      connection = new MySqlConnection(connString);
      adapter = new MySqlDataAdapter(query, connection);
      adapter.Fill(refreshDataTable);
    }

The current contents of the DataTable are cleared and then the table is refreshed by filling it using the MySqlDataAdapter with the revised query. Note that we don’t create a new DataTable object, so the Sort property we added when the table was created is still there. This means that the new data loaded into the table will still be sorted according to the year, month and day.

That’s all we need to do to refresh the DataGrid, since the DataGrid is bound to booksTable. Any changes to booksTable automatically are reflected in the DataGrid, and vice versa.

Editing data

By default, the cells in a DataGrid are editable, so to change the data for a particular issue, all we need to do is select the cell by double-clicking on it, and then type in the new text. Due to the data binding between the DataGrid and DataTable, these changes are automatically transmitted to the DataTable. However, these changes will not be passed on to the original MySQL database unless we write some code to make this happen. This is one place where using a MySQL database requires more hand-crafted code than using a DataSet for interacting with one of Microsoft’s databases such as SQL Server or Access. MySQL requires us to define a specific command for updating (or inserting and deleting) a record, so we need to see how to do this.

Since we want any change to the booksTable DataTable to be saved back to the MySQL database, we can add a handler for the RowChanged event in booksTable. We can do this by adding this line to the MainWindow() constructor:

      booksTable.RowChanged += new DataRowChangeEventHandler(booksTable_RowChanged);

The handler method is:

    void booksTable_RowChanged(object sender, DataRowChangeEventArgs e)
    {
      if (!changingTitle)
      {
        UpdateDBIssues();
      }
    }

Remember the ‘changingTitle’ variable we declared earlier? We need to call the UpdateDBIssues() method (which writes updates back to the MySQL database – we’ll look at it in a minute) only when the user actually makes changes to rows in the DataGrid by editing them. It turns out that when we change the title being viewed in the DataGrid, every row that gets inserted into booksTable by our call to GetTable() generates a RowChanged event, and if we called UpdateDBIssues() when that happened, we would end up duplicating all the records in the database. The ‘changingTitle’ parameter is a bit of a kludge, but it ensures that we update the database only when genuine changes to existing records have been made.

Now we need to see how to update the database. We have:

    private void UpdateDBIssues()
    {
      MySqlConnection connection = new MySqlConnection("server=localhost;uid=root;pwd=xxxx;database=comics;");
      string updateString = "UPDATE issues SET IssueTitle=?IssueTitle, Title=?Title, Volume=?Volume, Number=?Number, " +
        "IssueDay=?IssueDay, IssueMonth=?IssueMonth, IssueYear=?IssueYear, ComicVine=?ComicVine WHERE " +
        "Key_Issues=?oldKey_Issues";
      MySqlCommand updateCommand = new MySqlCommand(updateString, connection);
      updateCommand.Parameters.Add("?IssueTitle", MySqlDbType.VarChar, 100, "IssueTitle");
      updateCommand.Parameters.Add("?Title", MySqlDbType.Int32, 10, "Title");
      updateCommand.Parameters.Add("?Volume", MySqlDbType.Int32, 10, "Volume");
      updateCommand.Parameters.Add("?Number", MySqlDbType.VarChar, 10, "Number");
      updateCommand.Parameters.Add("?IssueDay", MySqlDbType.Int32, 10, "IssueDay");
      updateCommand.Parameters.Add("?IssueMonth", MySqlDbType.Int32, 10, "IssueMonth");
      updateCommand.Parameters.Add("?IssueYear", MySqlDbType.Int32, 10, "IssueYear");
      updateCommand.Parameters.Add("?ComicVine", MySqlDbType.VarChar, 100, "ComicVine");
      MySqlParameter parameter = updateCommand.Parameters.Add("?oldKey_Issues", MySqlDbType.Int32, 10, "Key_Issues");
      parameter.SourceVersion = DataRowVersion.Original;
      MySqlDataAdapter adapter = new MySqlDataAdapter();
      adapter.UpdateCommand = updateCommand;

      string insertString = "INSERT INTO issues (Key_Issues, IssueTitle, Title, Volume, Number, IssueDay, IssueMonth, IssueYear, ComicVine) " +
        "VALUES (?Key_Issues, ?IssueTitle, " + booksTitlesComboBox.SelectedValue + ", ?Volume, ?Number, ?IssueDay, ?IssueMonth, ?IssueYear, ?ComicVine)";
      MySqlCommand insertCommand = new MySqlCommand(insertString, connection);
      insertCommand.Parameters.Add("?Key_Issues", MySqlDbType.Int32, 10, "Key_Issues");
      insertCommand.Parameters.Add("?IssueTitle", MySqlDbType.VarChar, 100, "IssueTitle");
      insertCommand.Parameters.Add("?Volume", MySqlDbType.Int32, 10, "Volume");
      insertCommand.Parameters.Add("?Number", MySqlDbType.VarChar, 10, "Number");
      insertCommand.Parameters.Add("?IssueDay", MySqlDbType.Int32, 10, "IssueDay");
      insertCommand.Parameters.Add("?IssueMonth", MySqlDbType.Int32, 10, "IssueMonth");
      insertCommand.Parameters.Add("?IssueYear", MySqlDbType.Int32, 10, "IssueYear");
      insertCommand.Parameters.Add("?ComicVine", MySqlDbType.VarChar, 100, "ComicVine");
      adapter.InsertCommand = insertCommand;

      MySqlCommand deleteCommand = new MySqlCommand("DELETE FROM issues WHERE Key_Issues=?Key_Issues", connection);
      MySqlParameter delParameter = deleteCommand.Parameters.Add("?Key_Issues", MySqlDbType.Int32, 10, "Key_Issues");
      delParameter.SourceVersion = DataRowVersion.Original;
      adapter.DeleteCommand = deleteCommand;

      DataTable booksTable = (DataTable)((DataSourceProvider)FindResource("BooksTable")).Data;
      adapter.Update(booksTable);
    }

This method looks complicated, but it’s quite straightforward. We’ve included the code for inserting and deleting records as well, since we’ll be doing that shortly. Consider the update code. Lines 4 to 6 build the SQL for updating a record from the issues table. We need to add a parameter for each column we wish to update, and the names prefixed by a ? are place-holders for values that the command will read from booksTable for each row that has changed. The arguments to a call to Add() are: the place-holder name, such as ?IssueTitle, the data type of this parameter and the size of this data type (these can be read off the original definition in the database), and the name of the column to update.

The one special column is the Key_Issues column. This primary key is the one used to determine which record to update (it’s in the WHERE clause in the SQL). We determine which row to update by looking up the Key_Issues value. Line 16 adds this parameter to the command, and line 17 specifies that the value of Key_Issues is taken from the original version of the table (before the modification).

With the command and all its parameters built, we attach the command as the UpdateCommand property of the adapter on line 19. Similar commands are built for inserting and deleting rows on lines 21 to 37. Finally line 39 retrieves booksTable (the table containing the changed rows) and line 40 calls the Update() command, which is what actually writes the changes back to the MySQL database.

Deleting a row from the DataGrid is done by selecting the row and then pressing the Delete key.  By adding a handler for booksTable’s RowDeleted event which calls UpdateDBIssues(), the rows are also deleted from the original database.

Finally, we consider adding a new issue. This is most easily done by scrolling down to the last row in the DataGrid and typing in the new data, then hitting return. This adds a new row to booksTable, and since adding a row counts as a RowChanged event, UpdateDBIssues() is called and the ‘insert’ command adds the row to the database.

There’s one slight problem though. When we enter the data for a new row, we don’t specify the Key_Issues primary key. Ideally we would like this to be generated automatically. Fortunately, a DataTable has an AutoIncrement property for its columns. There’s one snag though: by default, AutoIncrement starts by assigning a value of 0 to the column and increments from there. In the MySQL database, of course, we will usually have a number of records already present, so the primary key Key_Issues will already be full up to some non-zero value. We therefore need to set the DataTable’s starting value equal to the maximum value of the column from the database. We can do that as follows. First, write a little method that gets the maximum value of a column:

    private int GetMaxKey(string column, string table)
    {
      string query = "SELECT max(" + column + ") FROM " + table + ";";
      MySqlConnection connection = new MySqlConnection("server=localhost;uid=root;pwd=xxxx;database=comics;");
      MySqlCommand maxCommand = new MySqlCommand(query, connection);
      maxCommand.Connection.Open();
      int maxKey = (int)maxCommand.ExecuteScalar();
      maxCommand.Connection.Close();
      return maxKey;
    }

This method uses SQL’s max() function to retrieve the maximum value of the given column from the given table. We use the ExecuteScalar() function to retrieve this single value. ExecuteScalar() returns the first element from a SQL query only, discarding the rest, and that’s just what we want here.

We use this value to set up the DataTable’s AutoIncrement property by inserting the following in MainWindow’s constructor:

      DataTable booksTable = (DataTable)((DataSourceProvider)FindResource("BooksTable")).Data;
      booksTable.Columns["Key_Issues"].AutoIncrement = true;
      booksTable.Columns["Key_Issues"].AutoIncrementSeed = GetMaxKey("Key_Issues", "issues") + 1;

This sets the AutoIncrement to start at one higher than the current maximum value, which is just what we need to synchronize the DataTable with the database. It is important that the primary key Key_Issues is not set to auto-increment in the MySQL database. The reason is that MySQL keeps track of the highest primary key value that has ever been used for a given table, which the Max() function returns the highest existing value for Key_Issues. If you’ve added some records and then deleted them, these two values will not be the same. By assigning the auto-increment to the DataTable only, we ensure that the same primary key is used both in the program and in the database.

By the way, even though it is easy enough to delete entries from the DataGrid by selecting them and pressing the delete key, it is sometimes handy to be able to do this in code. It took ages to discover how to do this, but I have a little method that does seem to work so I’ll throw it in here.

Suppose we add a button to the Books tab which will delete all selected rows when pressed. The event handler for this button will look like this:

    private void deleteButton_Click(object sender, RoutedEventArgs e)
    {
      if (booksDataGrid.SelectedItems.Count == 0) return;
      IList items = booksDataGrid.SelectedItems;
      IEnumerable<DataRowView> toDelete = items.Cast<DataRowView>();
      try
      {
        List<DataRowView> rows = new List<DataRowView>(toDelete);
        foreach (DataRowView row in rows)
        {
          row.Row.Delete();
        }
      }
      catch (InvalidCastException)
      {
        return;
      }
    }

On line 3, we check to make sure that at least one row is selected. Line 4 extracts a list of selected items from the DataGrid. This list is returned as a list that implements the IList interface, which is simply a list that can contain any data type, so at the moment the elements in this list are simply of the ‘object’ data type. Line 5 casts this list into an IEnumerable type whose elements are of type DataRowView (the view of a DataRow within a DataTable). The syntax in line 5 makes use of the Enumerable.Cast method, which is part of the System.Linq namespace, so you’ll need a ‘using System.Linq’ line at the top of your code file.

So far, so good, but there is a catch here. Since we want to delete elements from the DataTable (which, through data binding, will also delete rows from the DataGrid), we need to do it in such a way that we don’t disrupt the IEnumerable object. If we tried to delete objects directly from this object, we are trying to modify the collection while iterating over it, which will throw an exception. To get around this, we need to make a copy of the collection into an ordinary List, and use that for the iteration. That’s what we do on lines 8 to 12.

The try-catch block is there because after all the selected rows have been deleted, the DataGrid will position the selected row on the empty row at the bottom of the DataGrid if there are no other rows in the grid. This row has no associated entry in the DataTable, so attempting to access it throws an exception. There doesn’t seem to be any elegant way of detecting whether an row in the DataGrid has a partner in the DataTable, so it seems easiest to just catch the exception and ignore the error.

That completes the code for displaying a DataGrid bound to a DataTable, and allowing the user to edit, add and delete records from the database by editing the DataGrid. One final topic needs to be covered to complete the setup of this DataGrid, and that’s the configuration of the hyperlink column to display the links to the ComicVine website. We’ll have a look at that in the next post.

Using MySQL with WPF

MySQL is a popular free database which many (including me) prefer for writing database applications. Being relatively new to WPF, I wanted to see how MySQL could be used in a WPF application. This proved to be a fairly long journey, so we’ll probably need several posts to get through it all.

First, if you’re new to MySQL, you’ll need to download and install it. I won’t go into great detail here, apart from pointing you in the direction of the main download page for the free version (there are commercial versions that cost real money as well). After installing MySQL itself, you’ll need to install the MySQL ADO.NET connector in order to use it in WPF programming. This is currently located here, but if in the future this link is dead, just do a search for MySQL and ADO.NET.

With these two packages installed you should be ready to start writing code in Visual Studio (VS). The program I’ll discuss is a front end to an existing database, which allows you to insert, modify and delete records in the database. In homage to Sheldon Cooper, the database will contain details of my comic book collection. I’ll assume that you understand the basics of database construction, including the creation of tables and insertion of records into these tables. I’ll also assume you know the rudiments of SQL, since I’ll be using it to construct a few commands to be sent to the database. If you don’t know SQL very well (or at all) it shouldn’t hamper you too much since you can probably figure out what the commands are doing (SQL is fairly transparent at this level).

First, we’ll need to consider the structure of the database itself. It contains three tables, which contain the following fields:

Publishers (publishers of comic books)

  • Key_Publishers (the primary key)
  • Name (the name of the publisher)

Titles (titles of comic book series, not of individual issues)

  • Key_Titles (the primary key)
  • Title (the title’s name, such as Action Comics)
  • Publisher (an int giving the key of the publisher of this title)

Issues (individual issues of given titles)

  • Key_Issues (the primary key)
  • IssueTitle (the title of the individual issue)
  • Title (an int linking to the key in the Titles table)
  • Volume
  • Number
  • IssueDay
  • IssueMonth
  • IssueYear
  • ComicVine (the URL of the page on http://www.comicvine.com giving details about this issue)

The UI of the program consists of a tab control with three tabs: one for editing the issues, one for the titles and one for the publishers. We’ll consider the issues one first. It looks like this:

At the top is a ComboBox from which we can choose the title. Beneath this is a DataGrid in which we display the individual records from the data base for that title. At the bottom are a few boxes in which individual data for the selected issue are displayed. The user can edit the information either directly in the DataGrid, or by editing the boxes at the bottom.  The info in the boxes is identical to that displayed in the DataGrid except for the ComicVine link, which is shown as a URL in the text box, but as a hyperlink with the label ‘ComicVine’ in the DataGrid. This is done because the URL is usually far too long to be displayed conveniently in the grid, as you can see. The ‘Add’ button allows the user to add a new issue.

Clearly there’s a lot going on here, so we’ll need to take things step by step. To begin, let’s see how we can get the ComboBox to display the list of titles. (I’ll assume you can create the basic UI using Expression Blend (EB) or VS so I won’t go into that here.)

First, we need to let our VS project know we’ll be using MySQL. If you’ve installed the connecter mentioned above, you still need to include MySQL as a reference in your VS project. To do this, right-click on References in Solution Explorer and then click on the .NET tab. You may need to wait a few seconds while this list finishes loading, but eventually you can find MySQL.Data in the list, so you should add that. Now we can start writing some code.

Most of the linkage between controls and the MySQL database is done via data binding, which we’ve already looked at for simpler cases (see the index for a list of pages). Before we dive into the code it’s essential that you understand the structure of the program.

Ultimately the data are stored in the MySQL database, but the program itself doesn’t use this for the displays. First, the data must be loaded from the MySQL database into an internal data structure, which is then used for the main working of the program. Changes made by the user to the data using the UI affect only this internal representation of the data. If we want these changes to be made permanent, we need to write the code that will save these changes back to the original MySQL database.

WPF provides several internal data structures useful for storing information from a database. In fact, VS provides an automated way of creating a DataSet from database servers it has access to. Although you can create a DataSet from a MySQL server, the associated functionality provided by VS doesn’t seem to work with MySQL (at least I couldn’t find any way of making it work – there may be something that I haven’t discovered), so we need to write our own code to handle changes to the MySQL database. This isn’t that hard to do as we’ll see, but we’re getting ahead of ourselves.

Let’s see how we can access the data required to populate the ComboBox containing the list of Titles. From the above structure of the database, we see that the information is stored in the Titles table, so we need to load that data into the program. We’ve provided a separate class that handles this, and here’s the relevant code:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
//.....
class DatabaseTable
{
    MySqlConnection connection;
    MySqlDataAdapter adapter;
    public DataTable GetTable(String query, String sortBy)
    {
      String connString = "server=localhost;uid=root;pwd=xxxx;database=comics;";
      connection = new MySqlConnection(connString);
      adapter = new MySqlDataAdapter(query, connection);
      DataTable dataTable = new DataTable();
      adapter.Fill(dataTable);
      dataTable.DefaultView.Sort = sortBy;
      return dataTable;
    }
}

Note the ‘using’ statement that specifies the MySql library.

To get at data in a MySQL database we first need to connect to it, and that’s what the MySqlConnection is for. Its constructor requires a string giving the information needed to connect. In this case, we specify the server as ‘localhost’ which means it’s on the local machine. If you’re connecting to a remote server, you’d give the URL instead. The userID (uid) and password (pwd) are then given, followed by the name of the database.

Next, we need to create a MySqlDataAdapter, which is what does the actual work of retrieving the information from the database and storing it in the local object. In order for the adapter to get some data, it needs to know what to look for, and that’s what the ‘query’ string is for. This is an SQL command, which we’ll get to in a minute.

The adapter has to be given an object in which to store the data it retrieves. The standard data structure is the DataTable (in System.Data), which is essentially a single table of data. The Fill() method of MySqlDataAdapter executes the query on the MySQL database and loads the result in the DataTable. The DataTable will have columns with the same names as those in the original database, and it is these column names that can be used in data binding later on.

The last thing we do is define a sorting condition. Remember that whenever we bind a control to a data source such as a list, a collection view is automatically created and inserted between the data source and the control. This also applies to data binding between a control such as a ComboBox and a DataTable. The ComboBox displays the data as given by the collection view, so if we wish to sort the data as displayed in the UI, we add a sort command to the view. The data in the original DataTable is unchanged; all that changes is the way that data appears on screen.

In the case of a DataTable, we access its DefaultView as shown in the code, and then attach a Sort command to the view. The Sort is simply a string giving the sorting command we want. If we wish to sort the list of Titles, for example, we would specify ‘sortBy’ as “Title”, which is the name of the column we want to use as the sort key. (More complex sorting can be done too. We’ll see this when we consider the DataGrid showing the issues.)

There’s an important point here. Those of you familiar with SQL will know that we can include a sorting command as part of an SQL query, so you might be wondering why we didn’t just include the sorting command as part of the ‘query’ we sent to the database. The reason is that doing it this way would ask the MySQL database to do the sorting, so that the data used to populate the DataTable would be correctly sorted when it first arrives. However, if we then add extra rows to the DataTable by using our program, these rows would merely be tacked onto the end of the DataTable and would not be correctly sorted, since the DataTable hasn’t been told to sort its data. By putting the sort command into the DataTable rather that in the original SQL command, we ensure that the data as displayed in the program are always correctly sorted.

OK, we now have our internal DataTable, so how do we use this to populate the ComboBox? Fortunately, we’ve already considered data binding with a ComboBox, so we can model our code along that example. We’ll do things a little differently here, however, to illustrate a common technique for providing data sources in data binding.

We saw above that we provided the code for getting the DataTable in a class called DatabaseTable. We can access the DataTable by declaring an ObjectDataProvider in the XAML part of the code. In the Window.Resources section of the XAML, we can write:

<Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  mc:Ignorable="d"
  x:Class="Comics.MainWindow"
  x:Name="Window"
  xmlns:local="clr-namespace:Comics"
  xmlns:s="clr-namespace:System;assembly=mscorlib"
  Title="Comics"
  Width="680" Height="814">

  <Window.Resources>
    <ObjectDataProvider x:Key="TitlesTable"
    ObjectType="{x:Type local:DatabaseTable}"
    MethodName="GetTable">
      <ObjectDataProvider.MethodParameters>
        <s:String>SELECT * FROM titles</s:String>
        <s:String>Title</s:String>
      </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
  </Window.Resources>
  <!-- Code for UI -->
</Window>

This creates a resource with the name given as the Key (TitlesTable) by creating an object of the given type (DatabaseTable) and calling the indicated method (GetTable). The parameters passed to the method are given next, and in this case are two strings. The first string is the query to be sent to the MySQL database, and the second string is the Sort command, so that the DataTable sorts the records by Title.

Note that you’ll need to ensure that the various prefixes used in this XAML code are defined. Typically most of them are defined for you when you create a project in VS, but there are a couple that you’ll probably need to define yourself. Here, the ‘local’ namespace is the namespace used for the code in the project (Comics here). The ‘s’ namespace is required to define the String data type. (This is one reason why I hate XAML: although it is more compact in some cases, there is so much finicky stuff that it can be hard to get it right.)

We’re almost there. The last thing we’ll look at in this post is how to define the ComboBox so it gets its data from the ObjectDataProvider we just defined. The relevant line is:

            <ComboBox x:Name="booksTitlesComboBox" ItemsSource="{Binding Source={StaticResource TitlesTable}}" DisplayMemberPath="Title"
                    SelectedValuePath="Key_Titles" VerticalAlignment="Center" HorizontalContentAlignment="Stretch" Grid.Row="1" Grid.Column="1"
                    SelectionChanged="booksTitlesComboBox_SelectionChanged" FontWeight="Bold"/>

There’s a bit of stuff in here that we’ll get to later, but the relevant bits are:

  • ItemsSource is bound to the StaticResource TitlesTable that we just defined. This means that the items displayed in the ComboBox are bound to the items in that DataTable.
  • DisplayMemberPath is specified as ‘Title’. Since the DataTable contains more than one (two, actually) columns, we need to tell the ComboBox which column to display. The ‘Title’ is the textual title which the user can read.
  • SelectedValuePath: internally, we use the Key_Titles column for connecting a title with an issue (as we saw in the database tables above), so when the user selects an item from the ComboBox, we need to know the Key_Titles value in order to be able to retrieve the issues for that Title. More on this later when see how to populate the DataGrid.
  • SelectionChanged: when the user selects an item in the ComboBox, we need to update the display in the DataGrid to display all issues with that Title, so we provide an event handler to do this. Again, we’ll see how this works in a later post.

The program at this stage should display the list of titles in the ComboBox, although selecting an item won’t do anything yet. But that’s enough for one post, so we’ll continue the story in the next post.

Data binding with a ListBox and ComboBox in WPF

In the last post, we saw how to use data binding to a List to allow stepping through the elements of the List, displaying each item in separate TextBoxes. We also saw how a collection view provides an interface to the underlying List, and allows moving around the List as well as other operations like sorting and filtering.

However, when dealing with a list of objects, usually we would like a view that allows us to see several items in the list at the same time, and allows us to scroll through this display and select which item we want to deal with. To that end, we’ll have a look at how to bind a List to a ListBox and a ComboBox in WPF.

The program we use as illustration is an expanded version of the one from the previous post. The interface of the new program looks like this:

As before, we are looking at a list of books. Each book has an author, title, price and subject category. The available categories are shown in the ComboBox, while the titles of the books are displayed in a ListBox just above the buttons. Each category is represented by a unique integer code (so ‘physics’ has the code 2 in the picture). It is this numerical code that is stored in each Book object, so the textual representation of a given category is contained in a separate class called BookCategory. (Yes, I realize this example would be better done using a database, but for the purposes of illustrating data binding to lists, it serves its purpose.)

The buttons have the same functions as in the previous post (the First, Previous, Next and Last buttons move through the list of books, Add adds a new book to the list, Sort sorts the books by price and Cheap selects books with a price under 20.00. Nothing new here.

We’ve used data binding to keep the various parts of the interface synchronized. As we step through the list using one of the navigation buttons, the displays in the TextBoxes and ComboBox update to display the data in the current book, and the highlighted line in the ListBox also keeps in step with out current selection. If we select a book by clicking on a line in the ListBox, the rest of the display shows the data for that book. If we select a new category in the ComboBox, the Code box will update as well, and vice versa. (We haven’t put in any validation, so if you enter an invalid Code number, you won’t get an error message.)

The interface was built in Expression Blend as usual, so if you want to see the XAML for that, download the code (link at the end of the post) and have a look. We’ll look here at the code (all in C#) that does the binding between the lists and controls.

First, we’ll look at the classes that store the data that will be inserted into the lists. The Book class is slightly expanded from the previous post in order to accommodate the category code:

  class Book : INotifyPropertyChanged
  {
    public event PropertyChangedEventHandler PropertyChanged;
    protected void Notify(string propName)
    {
      if (this.PropertyChanged != null)
      {
        PropertyChanged(this, new PropertyChangedEventArgs(propName));
      }
    }

    string author;

    public string Author
    {
      get { return author; }
      set
      {
        if (author.Equals(value)) { return; }
        author = value;
        Notify("Author");
      }
    }

    string title;

    public string Title
    {
      get { return title; }
      set { if (title.Equals(value)) { return; }
        title = value;
        Notify("Title");
      }
    }

    decimal price;

    public decimal Price
    {
      get { return price; }
      set { if (price == value) { return; }
        price = value;
        Notify("Price");
      }
    }

    int categoryCode;

    public int CategoryCode
    {
      get { return categoryCode; }
      set { if (categoryCode == value) { return; }
        categoryCode = value;
        Notify("CategoryCode");
      }
    }

    public Book() { }
    public Book(string author, string title, decimal price, int code)
    {
      this.author = author;
      this.title = title;
      this.price = price;
      this.categoryCode = code;
    }
  }

Note, by the way, that the string returned in the Notify() call must match the name of the property in the code.

Next, we look at the BookCategory class:

  class BookCategory : INotifyPropertyChanged
  {
    public event PropertyChangedEventHandler PropertyChanged;
    protected void Notify(string propName)
    {
      if (this.PropertyChanged != null)
      {
        PropertyChanged(this, new PropertyChangedEventArgs(propName));
      }
    }

    int code;

    public int Code
    {
      get { return code; }
      set
      {
        code = value;
        Notify("Code");
      }
    }

    string category;

    public string Category
    {
      get { return category; }
      set
      {
        category = value;
        Notify("Category");
      }
    }

    public BookCategory(int code, string category)
    {
      Code = code;
      Category = category;
    }
  }

Again, no surprises here; it has the same form as the Book class.

Now we look at the binding code, contained in MainWindow.xaml.cs. The constructor is

    public MainWindow()
    {
      this.InitializeComponent();
      InitializeLibrary();
      InitializeCategoryList();
      UpdateButtonStates();
    }

After the standard InitializeComponent() call, we initialize the list of Books (the library) that is displayed in the ListBox and then the list of categories that is displayed in the ComboBox.

Here’s InitializeLibrary():

    ObservableCollection<Book> library;
    private void InitializeLibrary()
    {
      library = new ObservableCollection<Book>();
      library.Add(new Book("Feynman", "Feynman Lectures on Physics", BookPrice(), 2));
      library.Add(new Book("Asimov", "I, Robot", BookPrice(), 1));
      library.Add(new Book("Christie", "Death on the Nile", BookPrice(), 3));
      library.Add(new Book("Taylor", "From Sarajevo to Potsdam", BookPrice(), 4));
      LayoutRoot.DataContext = library;

      Binding listBoxBinding = new Binding();
      BindingOperations.SetBinding(booksListBox, ListBox.ItemsSourceProperty, listBoxBinding);
      booksListBox.DisplayMemberPath = "Title";
      booksListBox.SelectedValuePath = "CategoryCode";
      booksListBox.IsSynchronizedWithCurrentItem = true;
    }

We’re just hard-coding the first four books in the list. In more advanced code, you’d probably read them from a file and/or offer the user a way of entering the data in the interface (or, of course, read them from a database). Here we create a List of Books and set it as the data context.

Next we create a Binding and attach it to the list box (booksListBox is the ListBox that displays the books). The ItemsSourceProperty is set to this binding. Note that we don’t specify a Path for the binding itself. This causes the ListBox to bind to the entire data set in the data context. (Well, actually, it’s binding to the collection view that has been automatically wrapped around the List, as we saw in the previous post.) If we stopped at this point and ran the program, the ListBox would display a list of entires, each of which would say “ListBinding1.Book”. This is because, in the absence of any further instructions on how to display each element in the List, the ListBox calls the ToString() method of each object in the List. If no ToString() has been provided explicitly (we haven’t here), the default ToString() just prints out the data type of the object, which in this case is the Book class in the ListBinding1 namespace. In order to get something more informative to show up in the ListBox, we need to tell it which part of the Book object to display. That’s what the DisplayMemberPath is for. We set this to the name of the property of the Book that we want to show up; in this case, the Title. Note that DisplayMemberPath is a property of the ListBox and not of the binding. This can be a bit confusing, but if you think about it, it does make sense. The binding is concerned only with which element to display; the mechanics of what to display are handled by the UI control, in this case the ListBox.

The SelectedValuePath is a bit more subtle. List controls such as ListBoxes allow one property of the current item to be used for display, while reserving another property as the actual value of the item. The current item selected in a ListBox is the SelectedItem, and the value of this item is the SelectedValue. The SelectedValuePath tells the ListBox which property of the SelectedItem should be used for the SelectedValue. Thus SelectedValuePath is the name of a property and is not a value itself; the SelectedValue is the actual value of that property for the SelectedItem.

Finally we tell the ListBox to keep synchronized with the CurrentItem as specified in the collection view. If you don’t do this, the SelectedItem in the ListBox won’t change as you step through the Books in the collection view by using the navigation buttons.

If you ran the program at this point, you should see the titles displayed in the ListBox, and the highlighted item keep step with the CurrentItem as you use the buttons to move around the list. The ComboBox, however, will still be inert since we haven’t linked it into the program yet.

Now we look at the category list and how to bind it to the ComboBox. We use an ObservableCollection for this list as well, although in the current program there is no provision for adding or deleting categories, so we could have used an ordinary List with the same result. The code is:

    ObservableCollection<BookCategory> CategoryList;
    private void InitializeCategoryList()
    {
      CategoryList = new ObservableCollection<BookCategory>();
      CategoryList.Add(new BookCategory(1, "Science Fiction"));
      CategoryList.Add(new BookCategory(2, "Physics"));
      CategoryList.Add(new BookCategory(3, "Mystery"));
      CategoryList.Add(new BookCategory(4, "History"));
      Binding comboBinding = new Binding();
      comboBinding.Source = CategoryList;
      BindingOperations.SetBinding(categoryComboBox, ComboBox.ItemsSourceProperty, comboBinding);
      categoryComboBox.DisplayMemberPath = "Category";
      categoryComboBox.SelectedValuePath = "Code";

      Binding codeComboBinding = new Binding();
      codeComboBinding.Path = new PropertyPath("CategoryCode");
      BindingOperations.SetBinding(categoryComboBox, ComboBox.SelectedValueProperty, codeComboBinding);
    }

As with the book list, we are hard-coding a few categories for illustration; in real life you’d read these from a file or a database.

We begin by binding CategoryList to the combo box. Since CategoryList isn’t the data context, we need to specify it as the Source of the binding. As with the book list, we get the ComboBox to display the textual form of the category while using the numerical Code as its SelectedValue.

The semi-magical bit comes in the last 3 lines of code. Here we introduce a second binding for the ComboBox. This is a binding for the ComboBox’s SelectedValue, and we bind it to the CategoryCode property in the library (the list of Books). Note that we don’t specify a Source for this binding, so it will use the data context, which is the same library as the ListBox uses. By binding the ComboBox’s SelectedValue to the CategoryCode in the CurrentItem in the library, we synchronize the category displayed by the ComboBox to the category in the CurrentItem (the current Book being displayed). This means that if we change the category by typing a new number into the Code TextBox, then because that TextBox is bound to the CategoryCode in the Book, it will update that property. This in turn will cause the ComboBox’s SelectedValue to change. Then, due to the first binding between the CategoryList and the ComboBox, the new SelectedValue will be used to look up the corresponding DisplayMember, and the display of the ComboBox will be updated. The process also works in reverse: if you select a new category from the ComboBox, the same chain of events (in reverse) will cause the CategoryCode in the Book to change, which in turn will cause the Code TextBox to update.

There are only a couple of other minor changes that were made in this code compared to that in the previous post. The UpdateButtonStates() method has an extra line to ensure that the currently selected item in the ListBox is always visible, using the ScrollIntoView() method in ListBox:

    private void UpdateButtonStates()
    {
      CollectionView libraryView = GetLibraryView();
      previousButton.IsEnabled = libraryView.CurrentPosition > 0;
      nextButton.IsEnabled = libraryView.CurrentPosition < libraryView.Count - 1;
      booksListBox.ScrollIntoView(booksListBox.SelectedItem);
    }

Finally, the event handler for the Add button is modified to provide a category for a new book:

    private void addButton_Click(object sender, RoutedEventArgs e)
    {
      int newBookNum = library.Count + 1;
      library.Add(new Book("Author " + newBookNum, "Title " + newBookNum,
        BookPrice(), rand.Next(1, CategoryList.Count)));
      CollectionView libraryView = GetLibraryView();
      libraryView.MoveCurrentToLast();
      UpdateButtonStates();
    }

We generate the category randomly from those available in CategoryList.

Note that we didn’t need to change any of the logic for things like moving around the list, adding to the list, sorting or filtering. All of that is handled by the collection view, and the binding between the ListBox and ComboBox and the collection view works in exactly the same way as between the more cumbersome TextBox representation we used in the previous post.

Code available here.

Collection views in WPF

We’ve seen (for simple binding and also using converters to convert from one data type to another) how to use data binding to keep a dependency property of a control synchronized with the value of a field in an object. These examples, however, worked only when the data to which we were binding consisted of a single object. In real life, we often wish to bind to a list of data objects, so we’ll start having a look at that here.

We’ll use as an example the case where our data consists of a list of books. The interface displays the properties of a single book at a time, but we wish to be able to step through the list and display the properties of each book in order. As a bonus, we would also like to sort the books, and apply a filter to the list to pick out the cheapest books. The interface we’ll be using looks like this:

The buttons have the following effects:

  • First: go to the first book in the list.
  • Previous: go to the book immediately preceding the current book.
  • Next: go to the book immediately following the current book.
  • Last: go to the last book in the list.
  • Add: add a new book to the list.
  • Sort: sort the books in ascending order by price.
  • Cheap: display only those books with a price under 20.00.

The interface was constructed in Expression Blend and uses standard techniques. We won’t go into the interface here, but if you want a look, download the code (link at end of the post) and look at the MainWindow.xaml file.

Before we get into the code, we need to explain some of the theory behind data binding with lists. As you can see from the interface, the controls (TextBoxes) bind to the properties of only one book at a time, so somehow we need a way of extracting this information from the overall list. Also, we need a way of keeping track of where we are in the list so that the Previous and Next buttons work properly.

If all we were concerned with was creating a data structure which stores a list of books, we would create a Book class containing author, title and price fields, and then create a list of Books by using WPF’s built-in generic List type, as in List<Book>. We might then think that we’d be faced with having to write a lot of code to keep track of a position in the list (as well as do the sorting and filtering that we want in this case). However, WPF provides a magical interface called ICollectionView the implementation of which does all this for us. So what exactly is a collection view?

A collection view, as its name implies, provides a customizable view of a collection, such as a list. The job of the collection view is to allow us to move around the list, as well as performing other tasks such as sorting and filtering. As it’s a view, it provides a read-only interface to the list, so it’s not possible to change anything in the original list by means of the collection view.

A collection view is automatically created for us when we bind to a List object. That is, the act of defining a List object as a data context will create a collection view, and it is in fact this view that we bind to rather than the original List object itself. Once the view has been created, we can manipulate our position in the list, as well as sort and filter the list, by using methods of the view, rather than methods of the original list. At all times, it is the CurrentItem of the view that is used as the single data item within the list to which controls are bound. Thus changing the CurrentItem (for example, by stepping through the list) changes which item is bound to a control, with the result that the values displayed by the control change as we change the CurrentItem.

Let’s see how all this works in practice. First, we define the Book class, which must implement INotifyPropertyChanged since ultimately it is a Book object to which the controls bind. At this level, data binding works just the same way as in our earlier examples where we considered binding to a single object. The Book class should thus look familiar if you’ve read the earlier posts:

  class Book : INotifyPropertyChanged
  {
    public event PropertyChangedEventHandler PropertyChanged;
    protected void Notify(string propName)
    {
      if (this.PropertyChanged != null)
      {
        PropertyChanged(this, new PropertyChangedEventArgs(propName));
      }
    }

    string author;

    public string Author
    {
      get { return author; }
      set
      {
        if (author.Equals(value)) { return; }
        author = value;
        Notify("Author");
      }
    }

    string title;

    public string Title
    {
      get { return title; }
      set { if (title.Equals(value)) { return; }
        title = value;
        Notify("Title");
      }
    }

    decimal price;

    public decimal Price
    {
      get { return price; }
      set { if (price == value) { return; }
        price = value;
        Notify("Price");
      }
    }

    public Book() { }
    public Book(string author, string title, decimal price)
    {
      this.author = author;
      this.title = title;
      this.price = price;
    }
  }

Note that we’re using C#’s decimal data type to store the price, since we don’t want any round-off errors.

Next, we’ll look at creating a list of Books in which we can store a number of Books. However, rather than use the List generic type, we use an ObservableCollection instead. The reason for this is that this class implements the INotifyCollectionChanged interface, which means that any changes to the list (such as adding or deleting items) notify any controls bound to the list so they can update themselves. Apart from that difference, we can treat an ObservableCollection pretty much like a List. The relevant code from the MainWindow class is:

    public MainWindow()
    {
      this.InitializeComponent();
      InitializeLibrary(4);
      LayoutRoot.DataContext = library;
      UpdateButtonStates();
    }

    ObservableCollection<Book> library;
    private void InitializeLibrary(int numBooks)
    {
      library = new ObservableCollection<Book>();
      for (int i = 1; i <= numBooks; i++)
      {
        library.Add(new Book("Author " + i, "Title " + i, BookPrice()));
      }
    }

    Random rand = new Random();
    private decimal BookPrice()
    {
      decimal price = rand.Next(0, 5000) / 100m;
      return price;
    }

If you look in MainWindow.xaml, you’ll see that each of the three TextBoxes has its Text property bound to one of the fields in Book (that is, the Author TextBox is bound to the “Author” property, and so on).

We initialize the list of books by calling InitializeLibrary(). This merely generates a number of books with an author of “Author <number>” and a title of “Title <number>”; the price is a random value between 0.01 and 50.00.

On line 5, we define library as the data context of LayoutRoot (which is the Grid layout on which the interface is built). Since library is an ObservableCollection<Book>, this automatically creates a collection view which is wrapped around the list, and which will be used to determine which Book from the library is used as the current item to which the controls are bound. For example, if the current item is set to the first item in the list, then it is the first Book (the one with Author 1, etc) that is used in the binding to the three TextBoxes.

If we ran the code at this point (without even defining click event handlers for the buttons), the TextBoxes would display the properties from the first Book in library. In order to add functionality to the buttons and allow us to step through the list of Books in the library, we need to acquire and use the collection view.

First, how do we get hold of the collection view in the first place? There is a static method which allows this to be done:

    private CollectionView GetLibraryView()
    {
      return (CollectionView)CollectionViewSource.GetDefaultView(library);
    }

We need to provide an explicit cast to CollectionView, since the GetDefaultView() method is defined only as returning something that implements the ICollectionView interface. The CollectionView class is a WPF class that implements this interface and is in fact what GetDefaultView() returns. CollectionView also provides a few properties that aren’t defined in the ICollectionView interface, so it’s useful to deal with the class explicitly rather than just with the interface.

Note that GetDefaultView() does not create the collection view; that is done when the library is assigned as the data context. GetDefaultView() merely retrieves the collection view object that already exists. Thus successive calls to GetDefaultView() don’t erase any of the changes to the view that other method calls might make.

The first method that uses some of the view properties is the UpdateButtonStates() method that we call from the constructor above:

    private void UpdateButtonStates()
    {
      CollectionView libraryView = GetLibraryView();
      previousButton.IsEnabled = libraryView.CurrentPosition > 0;
      nextButton.IsEnabled = libraryView.CurrentPosition < libraryView.Count - 1;
    }

The view maintains a CurrentPosition marker which points at the location of the CurrentItem. Note that this is not necessarily the same as the position of the item in the original list, since a view can sort or filter the list items and generate a new order for the original items. All of this is done without affecting the data or its order in the original list; the view maintains a separate catalogue of the elements of the list and their new order.

UpdateButtonStates() disables the Previous button if CurrentPosition is 0. It also disables the Next button if the CurrentPosition is at the end of the view of the list. (Note that the Count property is not provided by ICollectionView; it is something that is added in the CollectionView class, which is one reason why we deal with the class explicitly.)

We can now add event handlers for the four buttons that move around the list:

    private void firstButton_Click(object sender, RoutedEventArgs e)
    {
      CollectionView libraryView = GetLibraryView();
      libraryView.MoveCurrentToFirst();
      UpdateButtonStates();
    }

    private void previousButton_Click(object sender, RoutedEventArgs e)
    {
      CollectionView libraryView = GetLibraryView();
      libraryView.MoveCurrentToPrevious();
      UpdateButtonStates();
    }

    private void nextButton_Click(object sender, RoutedEventArgs e)
    {
      CollectionView libraryView = GetLibraryView();
      libraryView.MoveCurrentToNext();
      UpdateButtonStates();
    }

    private void lastButton_Click(object sender, RoutedEventArgs e)
    {
      CollectionView libraryView = GetLibraryView();
      libraryView.MoveCurrentToLast();
      UpdateButtonStates();
    }

These should all be fairly obvious, since we’re using the methods from CollectionView to move around the list.

Next, we look at how we can sort the list. The event handler for the Sort button is:

    private void sortButton_Click(object sender, RoutedEventArgs e)
    {
      CollectionView libraryView = GetLibraryView();
      if (libraryView.SortDescriptions.Count != 0)
      {
        libraryView.SortDescriptions.Clear();
        sortButton.Content = "Sort";
      }
      else
      {
        libraryView.SortDescriptions.Add(new SortDescription("Price", ListSortDirection.Ascending));
        sortButton.Content = "Clear";
      }
      libraryView.MoveCurrentToFirst();
      UpdateButtonStates();
    }

A collection view maintains a list of SortDescriptions, which are applied in order. In this case, the Sort button is a toggle between a sorted and unsorted list. If there are SortDescriptions present (which would result in the list being sorted), we clear any existing SortDescriptions, which restores the list to its original order. If there are no SortDescriptions, then we add one which sorts the books by their price, in ascending order. In each case, we change the button’s caption to show what pressing it again will do.

Note that we don’t need to call a Sort() method to actually do the sorting; the simple act of adding a SortDescription to the view causes sorting to take place. If we had added a second SortDescription, then any books with the same price would be sorted according to the second SortDescription, and so on for further SortDescriptions. Remember that sorting affects only the order of the Books in the view; it does not change the order of the data in the original list.

Filtering is done by applying a Predicate (a condition which must be either true or false) to the list of Books, and retaining only those Books for which the Predicate is true. Again, note that filtering affects only the view of the list, and does not delete anything from the original list. Thus we could apply one filter that selects books with a price under 20.00, and then apply another filter for books over 20.00. Each filter would alter the view of the list, but not the list itself. The code for the filter is:

    private void filterButton_Click(object sender, RoutedEventArgs e)
    {
      CollectionView libraryView = GetLibraryView();
      if (libraryView.Filter != null)
      {
        libraryView.Filter = null;
        filterButton.Content = "Cheap";
      }
      else
      {
        libraryView.Filter = new Predicate<object>(book => ((Book)book).Price < 20);
        filterButton.Content = "All";
      }
      libraryView.MoveCurrentToFirst();
      UpdateButtonStates();
    }

Again, we are treating the filter button as a toggle between a filtered and unfiltered list. We’ve used the Predicate generic type defined in recent versions of C# (see here). The argument to the Predicate constructor tests if the Book’s price is less than 20. Again, all we need do is define the filter; we don’t need to call any explicit Filter() method.

Finally, we look at adding an element to the original list. Since a collection view doesn’t allow us to change the original list, we need to do this by dealing with the ObservableCollection<Book> object directly. Once we’ve added the new Book, we can then re-acquire the collection view for the new list. Because we defined the library as an ObservableCollection<Book>, any additions we make will be automatically notified to controls bound to the library, so the displays will be updated without the need for any further code.

    private void addButton_Click(object sender, RoutedEventArgs e)
    {
      int newBookNum = library.Count + 1;
      library.Add(new Book("Author " + newBookNum, "Title " + newBookNum, BookPrice()));
      CollectionView libraryView = GetLibraryView();
      libraryView.MoveCurrentToLast();
      UpdateButtonStates();
    }

This little program should give you a fair idea of what the collection view can do. There are a few other features as well, so have a stroll through the documentation to see what you can do. One thing this post doesn’t address, however, is how to display more than one element from a list at the same time, so we’ll get to that later.

Code available here.

Validation in WPF 1: Error reporting with a MessageBox

In the last couple of posts (here and here), we explored some of the aspects of data binding in WPF. The little application we wrote to illustrate data binding allowed the user to step through the integers, testing each one to see if it is prime or perfect. The user could also enter a number in a TextBox directly.

One bit of unfinished business was that the application didn’t deal with erroneous input correctly. WPF provides a validation mechanism which allows checking of user input to be done in a separate class.

Unfortunately, Expression Blend offers no facility for adding validation to an input control, so we need to edit the code by hand. It is possible to write validation code in either XAML or C#, but since I loathe writing XAML, and since we need to write some of the code in C# no matter what we do, I’ll take the path of writing all the binding and validation code for the TextBox’s Text property in C#.

If you’re starting with the project in the state arrived at in the last post, you’ll need to remove the binding for the Text property from the XAML line for numberTextBox. That is, you’ll need to remove the Text=”{Binding Number}” bit from that line. Alternatively, you can just download the code for this post from the link at the bottom, and follow along.

We now need to handle the data binding of the Number TextBox entirely within the C# code. Before we write the code, however, we’ll describe the process of validation.

When we bound the text in the TextBox to a data field in the PrimePerfect class, we (well, WPF, actually) did a conversion of the text in the TextBox to an int data type in the data field. If the user types something in the TextBox that doesn’t parse as an int, an exception will be thrown. The validation process catches this exception and can then generate a validation error, for which we can add an event handler.

Validation can be attached to a binding by adding a ValidationRule object to a binding’s ValidationRules collection. ValidationRule is an abstract class in the System.Windows.Controls namespace, so if we want to write our own validation rule, we need to inherit this class and implement its one method, which is called Validate().

However, a quick and dirty option is to use the ExceptionValidationRule class provided by WPF. This class implements ValidationRule, and all it does is forward the error message provided by the exception. For many applications this is enough, since exception error messages will usually tell you what’s gone wrong. However, if you want a nice user interface, or if you want to place other restrictions on the input that wouldn’t throw exceptions, you’ll need to provide your own custom ValidationRule implementation.

First, we’ll look at how to use ExceptionValidationRule, since this case includes most of the steps you’ll need for a custom validaton rule anyway. The code is contained in the constructor for MainWindow, which is in the MainWindow.xaml.cs code-behind file in the project.

    public MainWindow()
    {
      InitializeComponent();
      primePerfect = new PrimePerfect();
      baseGrid.DataContext = primePerfect;
      Binding numberTextBinding = new Binding();
      numberTextBinding.Path = new PropertyPath("Number");
      numberTextBinding.ValidationRules.Add(new ExceptionValidationRule());
      numberTextBinding.NotifyOnValidationError = true;
      Validation.AddErrorHandler(numberTextBox, numberTextBox_ValidationError);
      BindingOperations.SetBinding(numberTextBox, TextBox.TextProperty, numberTextBinding);
    }

Lines 4 and 5 create a PrimePerfect object and define it as the data context, as we described in the earlier post on data binding. Starting at line 6, we see how to define a data binding in C# as opposed to XAML. On line 6 we create an empty Binding object, and on line 7 we set its path to “Number”. This tells the binding to look for a data element named “Number” in the data context. On line 8, we add an ExceptionValidationRule object to this binding’s ValidationRules collection.

One peculiarity of validation is that a validation error event is not generated unless you explicitly ask for it. Line 9 does this by setting the binding’s NotifyOnValidationError property to ‘true’. If you set this property to ‘false’, this effectively turns off validation for this binding.

Line 10 adds an event handler for validation errors; in this case the handler is numberTextBox_ValidationError, which we’ll look at in a second. Notice that this is done by calling the static method AddErrorHandler in the Validation class, and it links the TextBox (not the individual binding!) with the error handler. This means that all validation errors for the TextBox will be directed to this handler. Usually this isn’t a problem, since most simple controls have only one place where the user can enter data, but in some cases you’ll need to sort out which part of the control is generating the validation error.

Finally, on line 11, connect the binding to the numberTextBox. Note that the second argument to SetBinding() is the property of the TextBox to which the binding is to be applied. This property must be a dependency property, which means it’s a property that can be set through various methods such as defining a style, or data binding. (It’s a bit of a circular definition, since we’re saying that data can be bound only to a dependency property, and a dependency property is a property to which data can be bound. Duh… Really, each control has to define which of its properties are dependency properties, and in practice, these are all the properties that you’d ever want to define through data binding.)

So this defines a binding and adds a validation error checker to it. The only remaining thing is to look at the validation error handler:

    void numberTextBox_ValidationError(object sender, ValidationErrorEventArgs e)
    {
      if (e.Action == ValidationErrorEventAction.Added)
      {
        MessageBox.Show((string)e.Error.ErrorContent, "Incorrect number or format");
      }
    }

This code displays a MessageBox containing an error message when a validation error occurs. However, it’s not quite that simple, as you can see from the ‘if’ statement (thanks to Stuart Birse for pointing this bit out). A validation error generates an event twice. The first time is when the error itself occurs (when the user enters some invalid data). The second time is when the error is cleared (for example, by the user deleting the incorrect data in the TextBox and entering some correct data). Both these events are directed to the same handler, so you need to check which type of event has occurred, and handle it appropriately. If you want to handle the case where the validation error has first occurred (the most common case), you need to check the Action field of the ValidationErrorEventArgs parameter and see if it’s equal to ValidationErrorEventAction.Added. We’ve done that here, and the result is a MessageBox displaying the error message, which is contained in the Error.ErrorContent property of the ValidationErrorEventArgs parameter. If you do need to do something when the validation error is cleared, you can check if the Action field of the ValidationErrorEventArgs parameter is equal to ValidationErrorEventAction.Removed. Note that if you don’t have this check in your event handler, you’ll get the MessageBox showing up both when the user enters incorrect data, and when the user clears this data and enters some correct data, which is most likely not what you want to happen.

It does seem a bit daft that these two events are handled by the same handler, since they are logically distinct, but I guess that’s just one of the foibles of WPF.

Runnning the program as it stands will now generate a validation error when the user enters something into the TextBox that can’t be parsed as an int, since that will throw an exception. However, we’d also like to prevent the user from entering integers less than 2. For that we need a custom validation rule.

Writing such a rule is quite simple. We define a class that inherits ValidationRule, and write the logic in the Validate() method. The code in the sample is as follows.

  using System.Windows.Controls;
  .......
  class NumberRangeRule : ValidationRule
  {
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
      int number;
      if (!int.TryParse((string)value, out number))
      {
        return new ValidationResult(false, "Must enter an integer >= 2");
      }
      if (number < 2)
      {
        return new ValidationResult(false, "Number must be >= 2");
      }
      return ValidationResult.ValidResult;
    }
  }

Note we need to access System.Windows.Controls to use the ValidationRule class. The logic in Validate() is pretty straightforward. We first try to parse the ‘value’ (the text in the TextBox in this case). If this fails, the TryParse() method returns false, and we return a ValidationResult object. The first argument to the constructor is a bool value that determines if a validation error is thrown. If its value is ‘false’, an error has occurred. The second parameter is the error message that will show up in the Error.ErrorContent ValidationErrorEventArgs parameter above.

If TryParse succeeds, the result of the parse is stored in ‘number’, and we then test the value of ‘number’ to see if it’s less than 2. If so, we generate another error, this time because the number is outside the required range. Note that this error would not throw an exception, so we need a custom validation rule to catch it.

Finally, if the data is valid we return the built in ValidationResult.ValidResult, which does not throw a validation error, so the error handler will not be called.

To use this custom rule, we merely replace line 8 in the first listing above with:

      numberTextBinding.ValidationRules.Add(new NumberRangeRule());

Everything will now work as before, except the error messages are generated by the custom rule.

The MessageBox provides accurate feedback if the user enters incorrect data, but it’s not very elegant. There are nicer ways of using validation to provide error messages, and we’ll look at those in a later post.

Code for this post available here.