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)的每个子项添加事件处理逻辑
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; namespace Controls
{
public partial class MainForm : Form
{
/// <summary>
/// 默认构造函数
/// </summary>
public MainForm()
{
InitializeComponent(); this.大图标ToolStripMenuItem.Click += new System.EventHandler(this.ToolStripMenuItem_Click);
this.详细信息ToolStripMenuItem.Click += new System.EventHandler(this.ToolStripMenuItem_Click);
this.平铺ToolStripMenuItem.Click += new System.EventHandler(this.ToolStripMenuItem_Click);
this.小图标ToolStripMenuItem.Click += new System.EventHandler(this.ToolStripMenuItem_Click);
this.列表ToolStripMenuItem.Click += new System.EventHandler(this.ToolStripMenuItem_Click);
} #region 鼠标右键勾选事件处理
/// <summary>
/// 设定右键菜单勾选项,设置ListView列表显示样式
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ToolStripMenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem tsMenumItem = sender as ToolStripMenuItem;
if (tsMenumItem.Checked)
{
return;//已经选中则返回
}
else
{
//清除勾选的右键菜单项
ClearCheckState(cmsStyle);
//勾选鼠标选中的右键菜单项
tsMenumItem.Checked = true;
}
//设置ListView列表显示样式
SetDisplayStyle(tsMenumItem.Text);
} /// <summary>
/// 清除勾选的右键菜单项
/// </summary>
/// <param name="cms">右键菜单</param>
private void ClearCheckState(ContextMenuStrip cms)
{
ToolStripMenuItem tsMenumItemTemp;
for (int i = ; i < cms.Items.Count; i++)
{
if (!(cms.Items[i] is ToolStripMenuItem))
{
continue;
}
tsMenumItemTemp = cms.Items[i] as ToolStripMenuItem;
if (tsMenumItemTemp.Checked)
{
tsMenumItemTemp.Checked = false;
}
}
} /// <summary>
/// 设置ListView列表显示样式
/// </summary>
/// <param name="name"></param>
private void SetDisplayStyle(string name)
{
foreach (ListViewItem lvi in listData.Items)
{
if (name == "详细信息")
{
lvi.ImageIndex = ;
}
else
{
lvi.ImageIndex = ;
}
}
switch (name)
{
case "大图标":
listData.View = View.LargeIcon;
break;
case "详细信息":
listData.View = View.Details;
break;
case "小图标":
listData.View = View.SmallIcon;
break;
case "列表":
listData.View = View.List;
break;
case "平铺":
listData.View = View.Tile;
break;
}
}
#endregion
}
}
6.运行效果如下所示: