我正在创建一个包含ListViewItems集合的listview,所有这些都带有复选框。我想检查项目是否已检查。我知道如何启动ItemChecked事件,但每次将ListViewItem添加到ListView时都会启动该事件。我怎么能阻止这个?
为了帮助您了解我想要做什么,这里有一些关于应用程序的信息。
我正在为红十字会调度员建立一个应用程序。它将帮助他们跟踪现场的单位。该应用程序用于记录传输等。当在传输期间进入priorety传输时,当前单元将被置于保持状态。这将通过选中属于ListViewItem单元的复选框来完成。
所以你看,我必须确保调度程序真正检查或取消选中ListViewItem。
我希望有人能指出我正确的方向。
答案 0 :(得分:1)
您可以设置一个标志,指示您正在插入项目,如果选中该标志,则忽略该事件。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
class Form1 : Form
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
ListView listView;
List<Unit> units;
bool insertingItem = false;
public Form1()
{
Controls.Add(listView = new ListView
{
Dock = DockStyle.Fill,
View = View.Details,
CheckBoxes = true,
Columns = { "Name" },
});
Controls.Add(new Button { Text = "Add", Dock = DockStyle.Top });
Controls[1].Click += (s, e) => AddNewItem();
listView.ItemChecked += (s, e) =>
{
Unit unit = e.Item.Tag as Unit;
Debug.Write(String.Format("Item '{0}' checked = {1}", unit.Name, unit.OnHold));
if (insertingItem)
{
Debug.Write(" [Ignored]");
}
else
{
Debug.Write(String.Format(", setting checked = {0}", e.Item.Checked));
unit.OnHold = e.Item.Checked;
}
Debug.WriteLine("");
};
units = new List<Unit> { };
}
Random Rand = new Random();
int NameIndex = 0;
readonly string[] Names = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" };
void AddNewItem()
{
if (NameIndex < Names.Length)
{
Unit newUnit = new Unit { Name = Names[NameIndex++], OnHold = Rand.NextDouble() < 0.6 };
units.Add(newUnit);
insertingItem = true;
try
{
listView.Items.Add(new ListViewItem { Text = newUnit.Name, Checked = newUnit.OnHold, Tag = newUnit });
}
finally
{
insertingItem = false;
}
}
}
}
class Unit
{
public string Name { get; set; }
public bool OnHold { get; set; }
}
答案 1 :(得分:1)
如果您使用ItemCheck事件而不是ItemChecked,则当新项目添加到列表时,事件将不。
//Counter to differentiate list items
private int counter = 1;
private void button1_Click(object sender, EventArgs e)
{
//Add a new item to the list
listView1.Items.Add(new ListViewItem("List item " + counter++.ToString()));
}
private void listView1_ItemCheck(object sender, ItemCheckEventArgs e)
{
//Get the item that was checked / unchecked
ListViewItem l = listView1.Items[e.Index];
//Display message
if (e.NewValue == CheckState.Checked)
MessageBox.Show(l.ToString() + " was just checked.");
else if (e.NewValue == CheckState.Unchecked)
MessageBox.Show(l.ToString() + " was just unchecked.");
}
答案 2 :(得分:0)
列表视图中有一个CheckedItems属性,您可以使用ListView.CheckedItems Property (System.Windows.Forms)