当 ListView 中的项目数发生变化时,Win Forms 中是否存在可以触发的事件?我尝试了大小和文本-奇怪的是,它们“排序”有效,但并非总是如此……
我试图触发一个标签来更新列表视图项的计数,因为它会在一百种方法中更改而无需手动执行。
如果您没有使用绑定数据源,您可以围绕 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");
}
}