C#winform中ListView及ContextMenuStrip的使用
标签:winform style blog http io color ar 使用 for
1.新建一个Windows窗体应用程序
2.添加文件夹及图片资源
文件夹图片(folder.png),文件图片(file.png)
3.在设计模式下添加控件
即:1个ListView(lvwData)、2个ImageList(imgLarge,imgSmall),1个ContextMenuStrip(cmsStyle),如下所示:
4.设置各控件详细属性
2个ImageList(imgLarge,imgSmall)添加Images、设置ImageSize(imgLarge--32*32, imgSmall--16*16),如下:
ContextMenuStrip(cmsStyle)添加Items,如下:
ListView(lvwData)要添加Items、Columns,绑定ContextMenuStrip(cmsStyle)、LargeImageList及SmallImageList
界面设计完成后,锁定所有控件,这是个好习惯~~
5.为ContextMenuStrip(cmsStyle)的每个子项添加事件处理逻辑
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Windows.Forms;
9
10 namespace Controls
11 {
12 public partial class MainForm : Form
13 {
14 ///
15 /// 默认构造函数
16 ///
17 public MainForm()
18 {
19 InitializeComponent();
20
21 this.大图标ToolStripMenuItem.Click += new System.EventHandler(this.ToolStripMenuItem_Click);
22 this.详细信息ToolStripMenuItem.Click += new System.EventHandler(this.ToolStripMenuItem_Click);
23 this.平铺ToolStripMenuItem.Click += new System.EventHandler(this.ToolStripMenuItem_Click);
24 this.小图标ToolStripMenuItem.Click += new System.EventHandler(this.ToolStripMenuItem_Click);
25 this.列表ToolStripMenuItem.Click += new System.EventHandler(this.ToolStripMenuItem_Click);
26 }
27
28 #region 鼠标右键勾选事件处理
29 ///
30 /// 设定右键菜单勾选项,设置ListView列表显示样式
31 ///
32 ///
33 ///
34 private void ToolStripMenuItem_Click(object sender, EventArgs e)
35 {
36 ToolStripMenuItem tsMenumItem = sender as ToolStripMenuItem;
37 if (tsMenumItem.Checked)
38 {
39 return;//已经选中则返回
40 }
41 else
42 {
43 //清除勾选的右键菜单项
44 ClearCheckState(cmsStyle);
45 //勾选鼠标选中的右键菜单项
46 tsMenumItem.Checked = true;
47 }
48 //设置ListView列表显示样式
49 SetDisplayStyle(tsMenumItem.Text);
50 }
51
52 ///
53 /// 清除勾选的右键菜单项
54 ///
55 /// 右键菜单
56 private void ClearCheckState(ContextMenuStrip cms)
57 {
58 ToolStripMenuItem tsMenumItemTemp;
59 for (int i = 0; i )
60 {
61 if (!(cms.Items[i] is ToolStripMenuItem))
62 {
63 continue;
64 }
65 tsMenumItemTemp = cms.Items[i] as ToolStripMenuItem;
66 if (tsMenumItemTemp.Checked)
67 {
68 tsMenumItemTemp.Checked = false;
69 }
70 }
71 }
72
73 ///
74 /// 设置ListView列表显示样式
75 ///
76 ///
77 private void SetDisplayStyle(string name)
78 {
79 foreach (ListViewItem lvi in listData.Items)
80 {
81 if (name == "详细信息")
82 {
83 lvi.ImageIndex = 1;
84 }
85 else
86 {
87 lvi.ImageIndex = 0;
88 }
89 }
90 switch (name)
91 {
92 case "大图标":
93 listData.View = View.LargeIcon;
94 break;
95 case "详细信息":
96 listData.View = View.Details;
97 break;
98 case "小图标":
99 listData.View = View.SmallIcon;
100 break;
101 case "列表":
102 listData.View = View.List;
103 break;
104 case "平铺":
105 listData.View = View.Tile;
106 break;
107 }
108 }
109 #endregion
110 }
111 }
6.运行效果如下所示:
C#winform中ListView及ContextMenuStrip的使用
标签:winform style blog http io color ar 使用 for
原文地址:http://www.cnblogs.com/makesense/p/4079835.html
评论