本例主要功能为跨线程为控件赋值,并且实现listview控件保持选中状态以及在可见区域显示
/// <summary>
/// 为控件赋值的委托
/// </summary>
/// <param name="realTimeRecord"></param>
delegate void SetListViewCallback2(List<CheckedItRecord> checkedItRecordList);
int itemIndex = -1;//初始化listview选中项的索引
#region 跨线程绑定发布列表
/// <summary>
/// 跨线程绑定发布列表
/// </summary>
/// <param name="realTimeRecord"></param>
private void SetListViewPublish(List<CheckedItRecord> checkedItRecordList)
{
// InvokeRequired需要比较调用线程ID和创建线程ID
// 如果它们不相同则返回true
if (this.listViewPublish.InvokeRequired)
{
SetListViewCallback2 d = new SetListViewCallback2(SetListViewPublish);
this.Invoke(d, new object[] { checkedItRecordList });
}
else
{
listViewPublish.Items.Clear();
foreach (CheckedItRecord checkedItRecord in checkedItRecordList)
{
ListViewItem lvitem = new ListViewItem();
lvitem.Tag = checkedItRecord.DeviceID.ToString();
lvitem.SubItems[0].Text = (Convert.ToString(checkedItRecord.BeginTime));
lvitem.SubItems.Add(Convert.ToString(checkedItRecord.EndTime));
lvitem.SubItems.Add(checkedItRecord.Editor);
List<CommonInfo> stateInfoListTemp = stateInfoList.FindAll(delegate(CommonInfo obj) { return obj.Code == Convert.ToString((int)checkedItRecord.SendState); });
lvitem.SubItems.Add(stateInfoListTemp[0].Type);
lvitem.SubItems.Add(checkedItRecord.EditTime);
lvitem.SubItems.Add(Convert.ToString(checkedItRecord.SendTime));
lvitem.SubItems.Add(checkedItRecord.SendInfoID.ToString());
lvitem.SubItems.Add(checkedItRecord.InfoID.ToString());
listViewPublish.Items.Add(lvitem);
}
if (this.itemIndex != -1)
{
//保证listview选中状态及可见性
this.listViewPublish.Items[this.itemIndex].Selected = true;
this.listViewPublish.Items[this.itemIndex].EnsureVisible();
}
}
}
#endregion