问题描述
对于一个列表框(选择"模式设置为一个"),我希望跟踪是否有选定项或没有选定项.为此,我为SelectedIndexChanged预订了一个方法,并检查SelectedIndex是否为-1.但是,我注意到,即使SelectedIndex更改为-1(如果尚未为-1),该事件在调用Items.Clear()之后也不会触发.
For a ListBox (With Selection mode set to One), I wish to track whether there's a selected item or none selected. To do so, I subscribed a method to SelectedIndexChanged and checked if the SelectedIndex is -1 or not. However, I noticed that the event doesn't fire after calling Items.Clear(), even though SelectedIndex changes to -1 (if it wasn't already -1).
为什么不开火?我知道我可以通过在清除列表之前将-1分配给SelectedIndex来解决此问题.但是有更好的方法吗?
Why doesn't it fire?I know I can work around this by assigning -1 to SelectedIndex before clearing the list. But is there a better way?
这是复制此代码的简单代码:
Here's a simple code to replicate this:
using System;
using System.Windows.Forms;
namespace ns
{
class Program
{
static ListBox lst = new ListBox();
public static void Main()
{
lst.SelectedIndexChanged += new EventHandler(lst_SelectedIndexChanged);
lst.Items.Add(1);
Console.WriteLine("Setting selected index to 0...");
lst.SelectedIndex = 0; //event fire here
Console.WriteLine("(Selected Index == {0})", lst.SelectedIndex);
Console.WriteLine("Clearing all items...");
lst.Items.Clear(); //event *should* fire here?!
//proof that the selected index has changed
Console.WriteLine("(Selected Index == {0})", lst.SelectedIndex);
}
static void lst_SelectedIndexChanged(object sender, EventArgs e)
{
Console.WriteLine("[!] Selected Index Changed:{0}", lst.SelectedIndex);
}
}
}
修改:我正在考虑通过制作从ListBox继承的类或通过制作用户控件来制作自定义列表.但是我不确定该如何处理.关于使用继承/userControl隐藏/覆盖clear方法的任何想法吗?是否还需要隐藏/覆盖其他方法,还是有办法避免这种情况?
I am considering making a custom list by making a class that inherits from ListBox, or by making a user control. However I'm not sure how to approach this.Any ideas on hiding/overriding the clear method using either inheritance/userControl?Would it require hiding/overriding other methods as well or is there a way to avoid this?
推荐答案
查看Reflector中的代码,Items上的Clear()方法仅重置.Net对象的内部对象列表(并且不会像您注意到的那样触发OnSelectedIndexChanged).
Looking at the code in Reflector, the Clear() method on Items just resets the .Net object's internal object list (and does not, as you noticed, fire OnSelectedIndexChanged).
SelectedIndex属性返回-1,因为该属性的getter中的逻辑指示如果内部列表中没有任何项,则应返回-1.
The SelectedIndex property returns -1 because the logic in the property's getter dictates that -1 should be returned if there are no items in the internal list.
这篇关于"SelectedIndexChanged";在"Items.Clear()"之后不触发在列表框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!