标志适用于 Windows 窗体/Web 窗体/移动窗体的 OnLoad 事件。在单选Listview中,不是多选,下面的代码实现起来很简单,并且可以防止多次触发事件。
当 ListView 取消选择第一个项目时,第二个项目是您需要的,并且集合应该只包含一个项目。
在移动应用程序中使用了以下相同的内容,因此某些集合名称可能与使用紧凑框架时有所不同,但适用相同的原则。
注意:确保 OnLoad 并填充您设置要选择的第一个项目的列表视图。
// ################ CODE STARTS HERE ################
//Flag to create at the form level
System.Boolean lsvLoadFlag = true;
//Make sure to set the flag to true at the begin of the form load and after
private void frmMain_Load(object sender, EventArgs e)
{
//Prevent the listview from firing crazy in a single click NOT multislect environment
lsvLoadFlag = true;
//DO SOME CODE....
//Enable the listview to process events
lsvLoadFlag = false;
}
//Populate First then this line of code
lsvMain.Items[0].Selected = true;
//SelectedIndexChanged Event
private void lsvMain_SelectedIndexChanged(object sender, EventArgs e)
{
ListViewItem lvi = null;
if (!lsvLoadFlag)
{
if (this.lsvMain.SelectedIndices != null)
{
if (this.lsvMain.SelectedIndices.Count == 1)
{
lvi = this.lsvMain.Items[this.lsvMain.SelectedIndices[0]];
}
}
}
}
################ CODE END HERE ################
理想情况下,应将此代码放入 UserControl 中,以便在单个选择 ListView 中轻松重用和分发。这段代码在多选中用处不大,因为该事件按其应有的行为工作。
我希望这会有所帮助。
亲切的问候,
Anthony N. Urwin
http://www.manatix.com