【发布时间】:2013-10-12 03:11:54
【问题描述】:
Win Forms 中是否有一个事件可以在 ListView 中的项目数发生变化时触发?我尝试了大小和文本 - 奇怪的是,它们“排序”有效但并非总是如此......
我试图触发一个标签来更新列表视图项的计数,因为它会发生变化,而无需在一百种方法中手动执行此操作。
【问题讨论】:
-
您的项目是手动输入的还是来自绑定的数据源?
标签: c# winforms events listview
Win Forms 中是否有一个事件可以在 ListView 中的项目数发生变化时触发?我尝试了大小和文本 - 奇怪的是,它们“排序”有效但并非总是如此......
我试图触发一个标签来更新列表视图项的计数,因为它会发生变化,而无需在一百种方法中手动执行此操作。
【问题讨论】:
标签: c# winforms events listview
如果您没有使用绑定的数据源,您可以围绕 ListView 控件创建一个包装器,并添加一个方法和一个事件以在将项目添加到您的 ListView 集合时触发一个事件。
自定义列表视图
public class customListView : ListView
{
public event EventHandler<CustomEventArgs> UpdateListViewCounts;
public void UpdateList(string data)
{
// You may have to modify this depending on the
// Complexity of your Items
this.Items.Add(new ListViewItem(data));
CustomEventArgs e = new CustomEventArgs(Items.Count);
UpdateListViewCounts(this, e);
}
}
public class CustomEventArgs : EventArgs
{
private int _count;
public CustomEventArgs(int count)
{
_count = count;
}
public int Count
{
get { return _count; }
}
}
用法示例
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
customListView1.UpdateListViewCounts+=customListView1_UpdateListViewCounts;
}
private void customListView1_UpdateListViewCounts(object sender, CustomEventArgs e)
{
//You can check for the originating Listview if
//you have multiple ones and want to implement
//Multiple Labels
label1.Text = e.Count.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
customListView1.UpdateList("Hello");
}
}
【讨论】: