Exercise: Create a ListBox with DataTemplates for playing cards

This exercise is provided to allow potential course delegates to choose the correct Wise Owl Microsoft training course, and may not be reproduced in whole or in part in any format without the prior written consent of Wise Owl.

The answer to the exercise will be included and explained if you attend the Wise Owl course listed below!

Category ==> WPF - Visual C#  (20 exercises)
Topic ==> Basic binding  (2 exercises)
Level ==> Average difficulty
Course ==> WPF using Visual C#
Before you can do this exercise, you'll need to download and unzip this file (if you have any problems doing this, click here for help).

You need a minimum screen resolution of about 700 pixels width to see our exercises. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

Open the window in the above folder, and make it the default window for your application.  When you run the application, you should see a combo box:

Combo box listing suits

A basic combo box bound to the SuitName property of the underlying class.  Take a peek at the code-behind to see that the underlying class exposes two public properties: SuitName and ImageName.

 

Change your combobox into a listbox (this should take seconds - they work the same way), then add a data template section to the listbox:

Start of data template

The start of the data template.

 

Within this data template for how the listbox appears, add:

  • A label with content bound to the SuitName of the underlying class; and
  • An image with image source bound to the ImageUrl property of the underlying class.

Here's a suggestion for how your listbox could look:

Listbox showing 4 suits

You should be able to select any suit.

 
 

Now attach an event to the MouseDoubleClick event of the ListBox, and in this event:

  1. create a variable lb of type ListBox which coverts the sender to a ListBox;
  2. convert the SelectedItem in this listbox into the underlying clsSuit object;
  3. Display the SuitName property of this suit.

Here is suggested code to do this!

private void lstSuit_MouseDoubleClick(object sender,

MouseButtonEventArgs e)

{

// get at the listbox just double-clicked on

ListBox lb = (ListBox)sender;

// show its suit

clsSuit suit = (clsSuit)lb.SelectedItem;

MessageBox.Show(suit.SuitName);

}

When you double-click on a suit, you should see a message as shown on the next page.

Here's the sort of message which you should get when you double-click on a suit:

Choosing a suit Displaying resulting suit
Double-click on a suit ... ... to see its name!

Reflecting on just how powerful WPF is (and just how time-consuming it can be) close down any windows you have open.

This page has 0 threads Add post