我有一个列表框和一个复选框(select all),在我的代码中,我调用listbox.items.clear()
,现在我想订阅这个事件,所以每当我的列表框被清除时,selectAll复选框也应该处于uncheck状态。
目前我正在处理这个在我的列表框SelectedIndexChanged事件,我找不到一个itemclear类型的事件在我的列表框事件列表
我真的想使用事件处理取消选中我的复选框。
这听起来像是往返。当您调用Clear
方法时,您知道您正在代码中清除它。在代码中React,不需要往返。
例如,创建一个helper方法来清除列表框,然后在清除列表框后执行您想要的代码。
据我所知,没有事件被引发为调用ListBox.Items.Clear
的直接结果。你可以实现你自己的行为:
public class CustomListBox : ListBox
{
public event EventHandler ItemsCleared;
public void ClearItems()
{
Items.Clear();
if(this.ItemsCleared != null)
{
this.ItemsCleared(this, EventArgs.Empty);
}
}
}
只需在Windows窗体应用程序中声明上面的类。不要使用标准的ListBox
,使用扩展的CustomListBox
并订阅ItemsCleared
事件。
不调用CustomListBox.Items.Clear
,调用CustomListBox.ClearItems
你是对的,没有这个事件。但为什么要这么复杂呢?定义一个像
这样的方法private void ClearAndUncheck(){
listbox.Items.Clear();
selectAll.Checked = false;
}
如果事件对您至关重要,我建议使用BindingList并绑定ListBox
,如果您的场景允许的话。这个方法可能会给你一些新的想法。
BindingList<string> myList;
myList = new BindingList<string>(...);
listBox1.DataSource = myList;
myList.ListChanged += new ListChangedEventHandler(myList_ListChanged);
然后,通过使用BindingList的ListChanged
事件(在许多其他事件中),当您的ListBox被ListBox1.Items.Clear().
清除时,您可以对"Select all"复选框进行操作
void myList_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.Reset)
{
... // Do what you need here
}
}