|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
Chapter 10 List ControlsThis chapter continues our discussion of Windows Forms controls available in the .NET Framework. The controls we saw in chapter 9 all presented a single item, such as a string of text or a button with associated text. In this chapter we will look at some controls useful for presenting collections of items in Windows-based applications. While it is certainly possible to use a multiline Textbox control to present a scrollable list of items, this control does not allow the user to select and manipulate individual items. This is where the ListBox and other list controls come in. These controls present a scrollable list of objects that can be individually selected, highlighted, moved, and otherwise manipulated by your program. In this chapter we will look at the ListBox and ComboBox controls in some detail. We will discuss the following topics:
Note that the ListView and TreeView classes can also be used with collections of objects. These classes are covered in chapters 14 and 15. We will take a slightly different approach to presenting the list controls here. Rather than using the MyPhotos application we have come to know and love, this chapter will build a new application for displaying the contents of an album, using the existing MyPhotoAlbum.dll library. This will demonstrate how a library can be reused to quickly build a different view of the same data. Our new application will be called MyAlbumEditor, and is shown in figure 10.1.
Figure 10.1 The MyAlbumEditor application does not include a menu or status bar. 10.1 List boxesA list box presents a collection of objects as a scrollable list. In this section we look at the ListControl and ListBoxclasses. We will create a list box as part of a new MyAlbumEditor application that displays the collection of photographs in a PhotoAlbum object. We will also support the ability to display our PhotoEditDlg dialog box for a selected photograph. Subsequent sections in this chapter will extend the capabilities of this application with multiple selection of photographs and the use of combo boxes. 10.1.1 Creating a list boxThe ListBoxand ComboBox controls both present a collection of objects. A list box displays the collection as a list, whereas a combo box, as we shall see, displays a single item, with the list accessible through an arrow button. In the window in figure 10.1, the photo album is displayed within a ComboBox, while the collection of photographs is displayed in a ListBox. Both of these controls are derived from the ListControlclass, which defines the basic collection and display functionality required in both controls. A summary of this class appears in .NET Table 10.1. .NET Table 10.1 ListControl classThe ListControl class is an abstract class for presenting a collection of objects to the user. You do not normally inherit from this class, instead the derived classes ListBox and ComboBox are normally used. This class is part of the System.Windows.Forms namespace, and inherits from the Control class. See .NET Table 4.1 on page 104 for a list of members inherited by this class.
Let’s see how to use some of these members to display the list of photographs contained in an album. The following steps create a new MyAlbumEditor application. We will use this application throughout this chapter to demonstrate how various controls are used. Here, we will open an album and display its contents in a ListBoxusing some of the members inherited from ListControl. Create the MyAlbumEditor project
Many of the above steps should be familiar to you if you have been following along from the beginning of the book. Since we encapsulated the PhotoAlbum and Photograph classes in a separate library in chapter 5, these objects, including the dialogs created in chapter 9, are now available for use in our application. This is quite an important point, so I will say it again: The proper encapsulation of our objects in the MyPhotoAlbum library in chapters 5 and 9 makes the development of our new application that much easier, and permits us to focus our attention on the list controls. With this in mind, let’s toss up a couple of buttons and a list so we can see how the ListBox control works. Create the controls for our new applicationSet the MyAlbumEditor application version number to 10.1 in the project’s AssemblyInfo.cs file.
Our form is now ready. You can compile and run if you like. Before we talk about this in any detail, we will add some code to make our new ListBox display the photographs in an album. Some of the new code added by the following steps mimics code we provided for our MyPhotos application. This is to be expected, since both interfaces operate on photo album collections. Display the contents of an album in the ListBox control
That’s it! No need to add individual photographs one by one or perform other complicated steps to fill in the list box. Much of the above code is similar to code we saw in previous chapters. The one exception, the UpdateList method, simply assigns the DataSource property of the ListBox control to the current photo album. protected void UpdateList()
{
lstPhotos.DataSource = _album;
}
The DataSource property is part of the data bindingsupport in Windows Forms. Data binding refers to the idea of assigning one or more values from some source of data to the settings for one or more controls. A data source is basically any array of objects, and in particular any class that supports the IList interface[1]. Since the PhotoAlbum class is based on IList, each item in the list, in this case each Photograph, is displayed by the control. By default, the ToString property for each contained item is used as the display string. If you recall, we implemented this method for the Photograph class in chapter 5 to return the file name associated with the photo. Compile and run your code to display your own album. An example of the output is shown in figure 10.2. In the figure, an album called colors.abm is displayed, with each photograph in the album named after a well-known color. Note how the GroupBox controls display their keyboard access key, namely Alt+A and Alt+P. When activated, the focus is set to the first control in the group box, based on the assigned tab order. You will also note that there is a lot of blank space in our application. Not to worry, these spaces will fill up as we progress through the chapter.
Figure 10.2 By default, the ListBox control displays a scroll bar when the number of items to display exceeds the size of the box. TRY IT!The DisplayMember property for the ListBox class indicates the name of the property to use for display purposes. In our program, since this property is not set, the default ToString property inherited from the Object class is used. Modify this property in the UpdateList method to a property specific to the Photograph class, such as “FileName” or “Caption.” Run the program again to see how this affects the displayed photographs. The related property ValueMember specifies the value returned by members such as SelectedValue. By default, the control will return the object instance itself. 10.1.2 Handling selected itemsAs you might expect, the ListBoxclass supports much more than the ability to display a collection of objects. Particulars of this class are summarized in .NET Table 10.2. In the MyAlbumEditor application, the list box is a single-selection, single-column list corresponding to the contents of the current album. There are a number of different features we will demonstrate in our application. For starters, let’s display the dialogs we created in chapter 9. .NET Table 10.2 ListBox classThe ListBox class represents a list control that displays a collection as a scrollable window. A list box can support single or multiple selection of its items, and each item can display as a simple text string or a custom graphic. This class is part of the System.Windows.Forms namespace, and inherits from the ListControl class. See .NET Table 10.1 on page 316 for a list of members inherited by this class.
The album dialog can be displayed using a normal button. For the PhotoEditDlg dialog, we would like to display the properties of the photograph that is currently selected in the list box. As you may recall, this dialog displays the photograph at the current position within the album, which seemed quite reasonable for our MyPhotos application. To make this work here, we will need to modify the current position to correspond to the selected item. The following steps detail the changes required to display our two dialogs. Display the property dialogs
In the code to display the Photograph Properties dialog, note how the SelectedIndex property is used. If no items are selected, then SelectedIndex will contain the value –1, and the current position in the album is not modified. When a photograph is actually selected, the current position is updated to the selected index. This assignment relies on the fact that the order of photographs in the ListBox control matches the order of photographs in the album itself. if (lstPhotos.SelectedIndex >= 0)
_album.CurrentPosition = lstPhotos.SelectedIndex;
For both dialogs, a C# using block ensures that any resources used by the dialog are cleaned up when we are finished. We also call UpdateList to update our application with any relevant changes made. In fact, neither property dialog permits any changes that we would display at this time. Even so, updating the list is a good idea in case we add such a change in the future. Compile and run your application to ensure that the dialog boxes display correctly. Note how easily we reused these dialogs in our new application. Make some changes and then reopen an album to verify that everything works as you expect. One minor issue with our application occurs when the album is empty. When a user clicks the photo’s Properties button, nothing happens. This is not the best user interface design, and we will address this fact in the next section. So far our application only allows a single item to be selected. List boxes often permit multiple items to be selected. This is our next topic. 10.2 Multi-selection list boxesSo far we have permitted only a single item to be selected from our list at a time. In this section we enable multiple item selection, and add some buttons to perform various actions based on the selected items. Specifically, we will add Move Up and Move Down buttons to alter the position of the selected photographs, and a Remove button to delete the selected photographs from the album. 10.2.1 Enabling multiple selectionEnabling the ListBoxto allow multiple selections simply requires setting the right property value, namely the SelectionMode property, to the value MultiSimple or MultiExtended. We discuss this property in detail later in the section. Whenever you enable new features in a control, in this case enabling multiple selection in our list box, it is a good idea to review the existing functionality of the form to accommodate the new feature. In our case, what does the Properties button in the Photographs group box do when more than a single item is selected? While we could display the properties of the first selected item, this seems rather arbitrary. A more logical solution might be to disable the button when multiple items are selected. This is, in fact, what we will do here. Since the Properties button will be disabled, we should probably have some other buttons that make sense when multiple items are selected. We will add three buttons. The first two will move the selected items up or down in the list as well as within the corresponding PhotoAlbum object. The third will remove the selected items from the list and the album. The steps required are shown in the following table. Enable multiple selections in the list box Set the MyAlbumEditor version number to 10.2.
You can compile and run this code if you like. Our new buttons do not do anything, but you can watch them become enabled and disabled as you select items in a newly opened album. We use the MultiExtendedselection mode setting, which permits selecting a range of items using the mouse or keyboard. This is one of four possible values for the SelectionMode enumeration, as described in .NET Table 10.3. TRY IT!Change the list box selection mode to MultiSimple and run your program to see how the selection behavior differs between this and the MultiExtended mode. Our next task will be to provide an implementation for these buttons. We will pick up this topic in the next section. .NET Table 10.3 SelectionMode enumerationThe SelectionMode enumeration specifies the selection behavior of a list box control, such as ListBox and CheckedListBox. This enumeration is part of the System.Windows.Forms namespace.
10.2.2 Handling the Move Up and Move Down buttonsNow that our list box allows multiple selections, we need to implement our three buttons that handle these selections from the list. This will permit us to discuss some collection and list box methods that are often used when processing multiple selections in a list. We will look at the Move Up and Move Down buttons first. There are two problems we need to solve. The first is that our PhotoAlbum class does not currently provide an easy way to perform these actions. We will fix this by adding two methods to our album class for this purpose. The second problem is that if we move an item, then the index value of that item changes. For example, if we want to move items 3 and 4 down, then item 3 should move to position 4, and item 4 to position 5. As illustrated in figure 10.3, if we first move item 3 down, it becomes item 4. If you then move item 4 down, you would effectively move the original item 3 into position 5.
Figure 10.3 When the third item in the list is moved down, the original fourth item moves into position 3. The trick here, as you may realize, is to move item 4 first, and then move item 3. In general terms, to move multiple items down, we must move the items starting from the bottom. Conversely, to move multiple items up, we must start at the top. We will begin with the new methods required in the PhotoAlbum class. Implement Move methods in PhotoAlbum class.Set the MyPhotoAlbum library version number to 10.2.
With these methods in place, we are ready to implement Click event handlers for our Move Up and Move Down buttons. These handlers are shown in the following steps. Handle the Move buttons
Both of these methods employ a number of members of the ListBoxclass. Let’s examine the Move Down button handler in detail as a way to discuss these items. private void btnMoveDown_Click(object sender, System.EventArgs e)
{
ListBox.SelectedIndexCollection indices = lstPhotos.SelectedIndices;
int[] newSelects = new int[indices.Count];
// Move the selected items down
for (int i = indices.Count - 1; i >= 0; i--)
{
int index = indices[i];
_album.MoveAfter(index);
newSelects[i] = index + 1;
}
_bAlbumChanged = true;
UpdateList();
// Reset the selections.
lstPhotos.ClearSelected();
foreach (int x in newSelects)
{
lstPhotos.SetSelected(x, true);
}
}
The following points are highlighted in the code. 1. Retrieve the selected items. A local indices variable is created to hold the index values of the selected items. The SelectedIndices property returns a ListBox.SelectedIndexCollectioninstance containing an array of the selected index values. The related SelectedItemsproperty returns the actual objects selected. Note that an array of integers is also created to hold the new index positions of the objects after they have been moved. 2. Move selected items down. Starting from the bottom of the list, each selected item is moved down in the album. Note that the MoveDown button is disabled if the last item is selected, so we know for certain that index + 1 will not produce an index which is out of range. 3. Update the list box. Once all the changes have been made to our album, we update the list box with the new entries. Note that this method has a side affect of clearing the current selections from the list. 4. Reselect the items. Once the list has been updated, the items need to be reselected. The newSelects array was created for this purpose. The ClearSelectedmethod is used to remove any default selections added by the UpdateList method, and the SetSelected method is used to select each entry in the array. You can run the application here if you like to see how these buttons work. The next section discusses the Remove button implementation. 10.2.3 Handling the Remove buttonThe Remove button is a bit like the Move Down button. We have to be careful that the removal of one item does not cause us to remove incorrect entries on subsequent items. We will again loop through the list of selected items started from the end to avoid this problem. Also note that by removing the selected photographs, we are making an irreversible change to the photo album. As a result, this a good place to employ the MessageBox class to ensure that the user really wants to remove the photos. Handle the Remove button
This code uses the SelectedItems property to retrieve the collection of selected objects. This property is used to determine how many items are selected so that our message to the user can include this information. int n = lstPhotos.SelectedItems.Count;
To perform the deletion, we use the SelectedIndices property to retrieve the index numbers of each selected object. Since our list is based on the PhotoAlbum class, we know that the index in the list box corresponds to the index in the album. Removing a selection is a simple matter of removing the object at the given index from the album. ListBox.SelectedIndexCollection indices = lstPhotos.SelectedIndices;
for (int i = indices.Count - 1; i >= 0; i--)
{
_album.RemoveAt(indices[i]);
}
Compile and run the application to see the Remove button and the rest of the interface in action. Note that you can remove photographs and move them around and still decide not to save these changes when the album is closed. If you look at our application so far, there is still some space available in the Albums group box. This space is intended for a ComboBox control holding the list of available albums. Now that we have seen different ways to use the ListBox control, it’s time to take a look at the other .NET list control: the ComboBox class. 10.3 Combo boxesA list box is quite useful for presented a list of strings, such as the photographs in an album. There are times when only one item will ever be selected, and when the extra space necessary to display a list box is problematic or unnecessary. The ComboBox class is a type of ListControl object that displays a single item in a text box and permits selection from an associated list box. Since a user can enter new values into the text box control, a ComboBox allows additional items to be added much more simply than a ListBoxcontrol. Features specific to the ComboBox class are shown in .NET Table 10.4. As you can see, a number of members are reminiscent of members from both the ListBox class and the TextBox class. The TextBox area of the control is sometimes called the editable portion of the control, even though it is not always editable, and the ListBox portion may be called the dropdown portion, since the list drops down below the text box portion for some display styles. .NET Table 10.4 ComboBox classThe ComboBox class is a ListControl object that combines a TextBox control with a ListBox object. A user can select an item from the list or enter an item manually. A ComboBox can be displayed with or without the list box portion shown and with or without the text box portion editable, depending on the setting of the DropDownStyle property. When the list box portion is hidden, a down arrow is provided to display the list of available items. This class is part of the System.Windows.Forms namespace, and inherits from the ListControl class. See .NET Table 10.1 on page 316 for a list of members inherited by this class.
10.3.1 Creating a combo boxIn our MyAlbumEditor application, we will add a ComboBox control to permit quick and easy access to the list of albums stored in the default album directory. The entries for this control will be taken from the album file names discovered in this directory, and the user will not be able to add new entries by hand. Figure 10.4 shows how our application will look after this change, with the ComboBox dropdown list displayed.
Figure 10.4 The dropdown list for a ComboBox is hidden until the user clicks on the small down-arrow to reduce the amount of space required for the control on the form. The steps required to create the combo box for our application are shown below. Replace Open button with a ComboBox control Set the MyAlbumEditor version number to 10.3.
As we saw for our ListBoxcontrol, the DataSource property provides a quick and easy way to assign a collection of objects to the cmbxAlbums control. In this case, the Directory.GetFiles method returns an array of strings containing the set of file names in the given directory that match the given search string. Our ComboBox is created with the DropDownStyle property set to DropDownList. This setting is taken from the ComboBoxStyle enumeration, and indicates that the list box associated with the combo box should not be displayed by default, and that the user cannot manually enter new values into the control. A complete list of values provided by the ComboBoxStyleenumeration is shown in .NET Table 10.5. .NET Table 10.5 ComboBoxStyle enumerationThe ComboBoxStyle enumeration specifies the display behavior of a combo box control. This enumeration is part of the System.Windows.Forms namespace.
Feel free to compile and run your program if you like. The combo box will display the available albums, without the ability to actually open an album. Opening an album requires that we handle the SelectedItemChanged event for our combo box, which is the topic of the next section. 10.3.2 Handling the selected itemOur ComboBox currently displays a selected album, but it doesn’t actually open it. The previous section replaced the Click handler for the now-deleted Open button with an OpenAlbum method, so all we need to do here is recognize when a new album is selected and open the corresponding album. The one issue we must deal with is the case where an invalid album exists. While we initialized our control to contain only album files ending with “.abm,” it is still possible that one of these album files contain an invalid version number or other problem that prevents the album from loading. The following steps handle this case by disabling the Properties button and ListBox control when such a problem occurs. An appropriate error message is also displayed in the title bar. Open the album selected in the combo box
This code provides both text and visual cues on whether the selected album was successfully opened. Note how the SelectedItem property is used to retrieve the current selection. Even though we know this is a string, the framework provides us an object instance, so ToString must be called to extract the actual text. string albumPath = cmbxAlbums.SelectedItem.ToString(); When the selected album opens successfully, the ListBox background is painted the normal window color as defined by the system and the Properties button in the Albums group box is enabled. Figure 10.1 at the beginning of this chapter shows the interface with a successfully opened album. When the album fails to open, the exception is caught and the title bar on the form is set to indicate this fact. In addition, the ListBox background is painted the default background color for controls and the Button controls are disabled. catch (Exception)
{
// Unable to open album
this.Text = "Unable to open selected album";
lstPhotos.Items.Clear();
lstPhotos.BackColor = SystemColors.Control;
btnAlbumProp.Enabled = false;
}
An example of this situation appears in figure 10.5. The specified album, badalbum.abm, could not be opened, and between the title bar and the window this fact should be pretty clear.
Figure 10.5 When the selected album cannot be loaded, only the Close button remains active. TRY IT!The ComboBox in our application does not allow the user to manually enter a new album. This could be a problem if the user has created some albums in other directories. To fix this, add a ContextMenu object to the form and associate it with the Albums group box. Add a single menu item called “Add Album…” to this menu and create a Click event handler to allow the user to select additional album files to add to the combo box via the OpenFileDialog class. Note that you have to modify the ComboBox to add the albums from the default directory manually within the OnLoad method. At present, since the DataSource property is assigned, the Items collection cannot be modified directly. Use BeginUpdate and EndUpdate to add a set of albums via the Add method in the Items collection, both in the OnLoad method and in the new Click event handler. The next section provides an example of how to handle manual edits within a combo box. 10.4 Combo box editsThe ComboBox created in the previous section used a fixed set of list entries taken from a directory on the disk. This permitted us to use the DataSource property for the list of items, and the DropDownList style to prevent the user from editing the text entry. In this section we will create another ComboBox that permits manual updates to its contents by the user. Such a control is very useful when there are likely to be only a few possible entries, and you want the user to create additional entries as necessary. It so happens that we have just this situation for the Photographer property of our Photograph class. Within a given album, there are likely to be only a handful of photographers for the images in that album. A combo box control is a good choice to permit the user to select the appropriate entry from the drop-down list. When a new photographer is required, the user can enter the new name in the text box. Figure 10.6 shows how this combo box will look. You may notice that this list only displays four photographers, whereas our album combo box displayed eight album files at a time. A ComboBox control displays eight items by default. We will shorten the size here so that the list does not take up too much of the dialog window.
Figure 10.6 Note how the dropdown for the ComboBox extends outside of the Panel control. This is permitted even though the control is contained by the panel. We will add this control to the MyAlbumEditor application in two parts. First we will create and initialize the contents of the control, and then we will support the addition of new photographers by hand. 10.4.1 Replacing the photographer controlThe creation of our combo box within the PhotoEditDlg form is much like the one we created for the MyAlbumEditor application, with the exception of a few settings. The steps required to create this control are shown in the following table. Add the photographer combo box Set the MyPhotoAlbum library version number to 10.4.
Note how this code uses both the SelectedItem and Text properties for the ComboBox control. The SelectedItem property retrieves the object corresponding to the item selected in the list box, while the Text property retrieves the string entered into the text box. Typically these two values correspond to each other, but this is not always true, especially when the user manipulates the text value directly, as we shall see next. 10.4.2 Updating the combo box dynamicallyWith our control on the form, we now need to handle manual entries in the text box. This is normally handled via events associated with the ComboBox control. The Validated event can be used to verify that an entry is part of the list and add it if necessary, and the TextChanged event can be used to process the text while the user is typing. We will look at both of these events. First, let’s add a Validated event handler, and then add code to auto-complete the entry as the user types. Validate the photographer entry
Our ComboBox is now updated whenever the user enters a new photographer, and the new entry will be available to other photographs in the same album. Another change that might be nice is if the dialog automatically completed a partially entered photographer that is already on the list. For example, if the photographer “Erik Brown” is already present, and the user types in “Er,” it would be nice to complete the entry on the user’s behalf. Of course, if the user is typing “Erin Smith,” then we would not want to prevent the user from doing so. This can be done by causing the control to select the auto-filled portion of the name as the user types. You will be able to experiment with this behavior yourself after following the steps in the subsequent table. Auto-complete the text entry as the user types
This code uses the FindString method to locate a match for the entered text. This method returns the index of the first object in the list with a display string beginning with the specified text. If no match is found, then a –1 is returned. int index = cmbxPhotographer.FindString(text);
When a match is found, the text associated with this match is extracted from the list and assigned to the text box portion of the control. if (index >= 0)
{
// Found a match
string newText = cmbxPhotographer.Items[index].ToString();
cmbxPhotographer.Text = newText;
The additional text inserted into the text box is selected using the SelectionStart and SelectionLength properties. The SelectionStart property sets the cursor location, and the SelectionLength property the amount of text to select. cmbxPhotographer.SelectionStart = text.Length;
cmbxPhotographer.SelectionLength = newText.Length - text.Length;
}
TRY IT!The list portion of the control can be forced to appear as the user types with the DroppedDownproperty. Set this property to true in the TextChanged handler to display the list box when a match is found. You may have realized that this handler introduces a slight problem with the use of the backspace key. When text is selected and the user presses the backspace key, the selected text is deleted rather than the previously typed character as a user would normally expect. Fix this behavior by handling the KeyPress event discussed in chapters 9 and 12 to force the control to delete the last character typed rather than the selected text. Before leaving our discussion of ListControl objects, it is worth noting that the controls we have discussed so far all contain textual strings. The .NET Framework automatically handles the drawing of these text strings within the list window. It is possible to perform custom drawing of the list elements, in a manner not too different than the one we used for our owner-drawn status bar panel in chapter 4. As a final example in this chapter, let’s take look at how this is done. 10.5 Owner-drawn listsTypically, your ListBox and ComboBox controls will each display a list of strings. You assign objects to the list, and the ToString method is used to retrieve the string to display in the list. The string value of a specific property can be displayed in place of the ToString method by setting the DisplayMember property for the list. The .NET Framework retrieves and draws these strings on the form, and life is good. There are times when you do not want to display a string, or when you would like to control exactly how the string looks. For these situations you must draw the list manually. This is referred to as an owner-drawn list, and the framework provides specific events and other mechanisms for drawing the list items in this manner. In this section we modify our main ListBox control for the application to optionally include a small representation of the image associated with each photograph. Such an image is sometimes called a thumbnail, since it is a “thumbnail-sized” image. An example of our list box displaying these thumbnails is shown in figure 10.7. As you can see, the list includes a thumbnail image as well as the caption string from the photograph.
Figure 10.7 The ListBox here shows both the image and the caption for each photograph. Note how none of the items are selected in this list. We will permit the user to switch between the thumbnail and pure text display using a context menu associated with the list box. This menu will be somewhat hidden, since users will not know it exists until they right-click on the list control. A hidden menu is not necessarily a good design idea, but it will suffice for our purposes. We will begin our example by adding this new menu. 10.5.1 Adding a context menuSince we would like to dynamically switch between an owner-drawn and a framework-drawn control, we need a way for the user to select the desired drawing method. We will use a menu for this purpose, and include a check mark next to the menu when the thumbnail images are shown. Context menus were discussed in chapter 3, so the following steps should be somewhat familiar. Add a context menu Set the MyAlbumEditor version number to 10.5.
The Click handler for our new menu simply toggles its Checked flag and sets the drawing mode based on the new value. The DrawMode property is used for both the ListBox and ComboBox controls to indicate how each item in the list will be drawn. The possible values for this property are shown in .NET Table 10.6. Since the size of our photographs in an album may vary, we allow the size of each element in the list to vary as well. As a result, we use the DrawMode.OwnerDrawVariable setting in our code. The ItemHeight property contains the default height for each item in the list. When the DrawMode property is set to Normal, we set this property to the height of the current font plus 2 pixels. For our owner-drawn list, the item height depends on the size of the photograph we wish to draw. This requires that we assign the item height dynamically, and is our next topic. .NET Table 10.6 DrawMode enumerationThe DrawMode enumeration specifies the drawing behavior for the elements of a control. This enumeration is part of the System.Windows.Forms namespace. Controls that use this enumeration include the ListBox, CheckedListBox, and ComboBox classes, although the Checked | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||