Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# ПІДРУЧНИКИ / c# / Manning - Windows.forms.programming.with.c#.pdf
Скачиваний:
108
Добавлен:
12.02.2016
Размер:
14.98 Mб
Скачать

ADD EVENT HANDLERS FOR THE VIEW MENU (continued)

 

Action

Result

 

 

 

9

Add Click event handlers

private void menuLargeIcons_Click

 

for each of the four menus

(object sender, System.EventArgs e)

 

in the View menu.

{

 

listViewMain.View = View.LargeIcon;

 

 

 

Note: These handlers set

}

 

the View property value in

private void menuSmallIcons_Click( . . . )

 

the listViewMain control,

 

{

 

which alters how the con-

listViewMain.View = View.SmallIcon;

 

tents of the control appear

}

 

to the user.

private void menuList_Click( . . . )

 

 

 

 

{

 

 

listViewMain.View = View.List;

 

 

}

 

 

private void menuDetails_Click( . . . )

 

 

{

 

 

listViewMain.View = View.Details;

 

 

}

 

 

 

Your program will work just fine here. It doesn’t do very much, but it does work. Our final step for this section is to populate the list control with the available albums.

14.2.3Populating a ListView

Our final task here is to populate the ListView control. As we said earlier in the chapter, a ListView control contains a collection of ListViewItem objects. As indicated in .NET Table 14.3, the ListViewItem object inherits directly from the Sys-

tem.Object class. All of the painting and other management of list items are performed by the ListView class itself. This painting behavior is consistent with other container controls we have seen such as the StatusBar control containing StatusBarPanel objects, and the ListBox control containing a set of object instances.

Our use of the ListViewItem object here will be fairly modest. We will get more complicated later in the chapter. For now, we simply wish to create an item for each album with the file name as the label and an appropriate image icon assigned. This requires that we create an ImageList for both the small and large icons to display in the view, and populate the Items property for the list with a ListViewItem for each album.

448

CHAPTER 14 LIST VIEWS

.NET Table 14.3 ListViewItem class

The ListViewItem class is an object that can be displayed within a ListView control. It is part of the System.Windows.Forms namespace, and supports the IClonable and ISerializable interfaces.

 

ListViewItem

Initializes a new ListViewItem instance.

 

 

Overloads

Public

 

ListViewItem(string label);

Constructors

 

ListViewItem(string[] labelAndSubitems);

 

ListViewItem(string label, int imageIndex);

 

 

 

 

ListViewItem(ListViewItem item,

 

 

ListViewSubItem[] subitems,

 

 

int imageIndex);

 

 

 

 

Bounds

Gets the bounding rectangle of the item, including any

 

 

displayed subitems.

 

Focused

Gets or sets whether the item has the focus within the

 

 

containing view. Defaults to false.

 

Font

Gets or sets the Font for the item. If null, the containing

 

 

ListView uses its font for this purpose.

 

ForeColor

Gets or sets the foreground Color for the item.

 

ImageIndex

Gets or sets the index used to retrieve the icon for this item.

Public

Index

Gets the index corresponding to the current position of the

 

item within the containing ListView.

Properties

ListView

Gets the ListView control that contains this item.

 

 

Selected

Gets or sets whether the item is currently selected in the

 

 

containing view.

 

StateImageIndex

Gets or sets the index for the state icon for this item.

 

SubItems

Gets the collection of list view subitems assigned to this

 

 

item. Note that this includes the item label as the first

 

 

element in this collection.

 

Tag

Gets or sets the object associated with this item.

 

Text

Gets or sets the text string for this item. This is the item label.

 

 

 

 

BeginEdit

Initiates an edit of this item’s label.

Public

EnsureVisible

Ensures a given item is visible, scrolling the containing

 

view as necessary.

Methods

 

 

 

 

Remove

Removes the item from the collection of ListViewItem

 

 

objects in the containing view.

 

 

 

THE LISTVIEW CLASS

449

We will begin with the ImageList components.

CREATE THE IMAGE LISTS FOR THE VIEW

 

 

 

 

 

Action

Result

 

 

 

 

 

 

 

 

 

 

 

 

1

In the MainForm.cs [Design] window, add

The objects appear in the component tray area

 

two new ImageList objects to the form.

below the form.

 

 

 

 

 

Settings

 

Note: The first list will contain the large

 

 

 

List

 

Property

Value

icons for the View.LargeIcon display

 

 

 

List 1

 

(Name)

imageListLarge

mode, and the second the small icons for

 

 

 

 

all other modes. Since the icons provided

 

 

 

 

 

Size

32. 32

 

 

 

 

 

 

 

 

 

 

 

in the common image area define both

 

 

 

List 2

 

(Name)

imageListSmall

image types, each list will use the same

 

 

 

 

 

Size

16, 16

 

 

 

set of files. The Size property defines the

 

 

 

 

 

 

 

 

 

 

 

actual image to use by each list.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

2

Define the images from the common

The icons are stored in the image list and

 

image area required for the

available to the application.

 

imageListLarge object.

Note: The first icon will be used for Pho-

 

How-to

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

tograph objects later in this chapter. The

 

Use the Image Collection Editor, as

next two are for a “good” and “bad”

 

discussed in chapter 13.

album, respectively. The final three will be

 

 

 

 

 

Settings

used in chapter 15 when discussing the

 

 

 

 

 

TreeView class.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Image

 

 

 

File

 

 

 

 

 

 

 

 

0

 

icons/Misc/FACE01.ico

 

 

1

 

icons/Writing/BOOK01A.ico

 

 

2

 

icons/Misc/MISC02.ico

 

 

3

 

icons/Misc/FACE02.ico

 

 

4

 

icons/Writing/BOOK02.ico

 

 

5

 

icons/Writing/BOOKS04.ico

 

 

 

 

 

 

 

 

 

 

 

 

 

3

Similarly, define the same set of images

The same set of icons, albeit in different sizes,

 

for the imageListSmall object.

is now available from both image lists.

 

Note: You might be tempted to create

 

 

this image list by making a copy of the

 

 

imageListLarge object and then apply-

 

 

ing the settings from step 1. While this

 

 

works, the small images are scaled from

 

 

the larger size stored in the image-

 

 

ListLarge object, resulting in poorer

 

 

quality icons.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

4

Assign the two image lists to the

Images from each list can now be displayed for

 

corresponding property in the ListView

items in the ListView control.

 

control.

 

 

 

 

 

 

 

 

 

 

 

 

 

Settings

 

 

 

 

 

 

 

 

 

 

 

Property

 

Value

 

 

 

 

LargeImageList

 

imageListLarge

 

 

 

 

SmallImageList

 

imageListSmall

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

450

CHAPTER 14 LIST VIEWS

The code generated by these changes is similar to examples we have seen before. The images are stored in a .resx file for the MainForm object, and loaded into the application using the ResourceManager class.

Now that we have the image lists defined, the form containing a ListView control, and the View menu primed and ready, we have nothing to do but add our photo albums to the list. We do this in the OnLoad method, which is called just before the Form displays the first time. We could instead add these items in the MainForm constructor, but the OnLoad method is preferred for such actions to ensure that the Form is fully initialized.

Let’s see how this code looks.

ADD EACH ALBUM TO THE VIEW

 

Action

Result

 

 

 

5

In the MainForm.cs source code

using System.IO;

 

window, indicate that this file will

using Manning.MyPhotoAlbum;

 

use members of the System.IO

 

 

and the Manning.MyPhotoAlbum

 

 

namespaces.

 

 

 

 

6

Add a set of constant fields for the

private const int PhotoIndex = 0;

 

image list indices required.

private const int AlbumIndex = 1;

 

Note

private const int ErrorIndex = 2;

 

 

 

Using constants in this manner is a

 

 

good idea in case our values ever

 

 

change in the future.

 

 

 

 

7

Modify the OnLoad method to load

protected override void OnLoad(EventArgs e)

 

the default set of albums through a

{

 

private method.

. . .

 

LoadAlbumData(PhotoAlbum.DefaultDir);

 

 

 

 

}

 

 

 

8

Create a private OpenAlbum method

private PhotoAlbum OpenAlbum(string fileName)

 

to open an album.

{

 

 

PhotoAlbum album = new PhotoAlbum();

 

 

try

 

 

{

 

 

album.Open(fileName);

 

 

}

 

 

catch (Exception)

 

 

{

 

 

return null;

 

 

}

 

 

return album;

 

 

}

 

 

 

THE LISTVIEW CLASS

451

settings.
Photo-

ADD EACH ALBUM TO THE VIEW (continued)

 

Action

Result

 

 

 

9

Implement the LoadAlbumData

private void LoadAlbumData(string dir)

 

method by iterating over the set of

{

 

album files in the given album

string[] albumFiles

 

= Directory.GetFiles(dir, "*.abm");

 

directory.

 

foreach (string s in albumFiles)

 

Note: Accepting the directory from

{

 

 

 

which to load the albums may

 

 

come in useful if we ever want to

 

 

support multiple directories.

 

 

 

 

10

Try to open the album file.

// See if we can open this album

 

 

PhotoAlbum album = OpenAlbum(s);

 

 

Note: Of course, if the album requires a pass-

 

 

word, then the user must enter it here, which is

 

 

not the best user interface. See the TRY IT! para-

 

 

graph later in this section for a discussion on an

 

 

alternative approach.

 

 

 

11

Initialize a new ListViewItem

// Create a new list view item

 

based on whether the album was

ListViewItem item = new ListViewItem();

 

opened successfully.

item.Text

 

 

 

 

= Path.GetFileNameWithoutExtension(s);

 

 

if (album != null)

 

 

item.ImageIndex = MainForm.AlbumIndex;

 

 

else

 

 

item.ImageIndex = MainForm.ErrorIndex;

 

 

 

12

Add the new item to the ListView

listViewMain.Items.Add(item);

 

control.

}

 

 

}

 

 

 

This creates a list item for each album found, using the base file name as the text for the album. If an album fails to open, then an error image is assigned as its icon. If any of your albums happen to have a nonempty password set, then the PhotoAlbum class will prompt you for this password before opening the album.

As you progress through this chapter, you will note that the album password is required repeatedly as the album is opened, which is not of course the nicest interface one could ask for. We could fix this by only requiring the password in the

Album class when the user wants to examine the photos or modify the album We will not actually do this, but we could.

Compile and run this program to see our new list view at work. Also alter the display setting using the items in the View menu. Assuming you have some album files in the album directory, you should find that the Large Icons, Small Icons, and List menus work just fine. Curiously, the Details setting displays nothing at all.

This is because the Details view requires a set of columns to be assigned to the form. So far we have not done this, so we will make it our next topic.

452

CHAPTER 14 LIST VIEWS

Соседние файлы в папке c#