我有一个继承Form.ComboBox类的自定义ComboBox。它的DataSource受到约束。 其属性初始化如下:
this.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.DropDownStyle = ComboBoxStyle.DropDown;
OnDropDown将其AutoCompleteMode设置为None,然后在OnDropDownClosed中再次设置为Suggest(以避免在此处解决问题WinForms ComboBox DropDown and Autocomplete window both appear)
我有一个实现的逻辑,用于验证ComboBox并在键入某些文本时选择第一个匹配的项目。
当显示DropDown并且用户键入内容并按Enter键时,将选择第一个匹配项。然后我想关闭DropDown。我通过将ComboBox.DroppedDown属性设置为false来实现。问题是当DropDown以这种方式关闭时,所选项目将重置为先前选定的项目。 OnSelectedIndexChanged,OnSelectionChangeCommitted和OnSelectedValueChanged都没有被调用。
我通过记住在OnSelectedIndexChanged中选择的索引并在OnDropDownClosed中再次设置它来处理它(在条件下DropDown是手动关闭的)。
问题: 当DroppedDown属性ComboBox设置为false时,为什么选中的项,索引,文本和值重置?还有另一种手动关闭ComboBox但没有副作用的方法吗?
编辑:解决问题的代码:
List<string> list = new List<string>();
list.Add("item0");
list.Add("item1");
list.Add("item2");
list.Add("item3");
list.Add("item4");
customComboBox1.DataSource = list;
...
public class CustomComboBox : ComboBox
{
public CustomComboBox(){ }
#region OnKeyDown
protected override void OnKeyDown(KeyEventArgs e)
{
if (!this.Enabled) e.Handled = true;
else
{
base.OnKeyDown(e);
if (e.KeyCode == Keys.Enter)
{
this.SelectedIndex = 2; // index changes here
Console.WriteLine("ENTER - before DroppedDown=false " +
this.SelectedIndex + " " + this.Text);
if (this.DroppedDown)
{
// here index = 2, text = Item2
this.DroppedDown = false;
// here index = previous index, text is still Item2
// different thing is displayed than is actually chosen
// OnSelectedIndexChanged wasn't raised
}
Console.WriteLine("ENTER - after DroppedDown=false " +
this.SelectedIndex + " " + this.Text);
e.Handled = true;
}
}
}
#endregion
#region OnSelectedIndexChanged
protected override void OnSelectedIndexChanged(EventArgs e)
{
Console.WriteLine("OnSelectedIndexChanged " +
this.SelectedIndex + " " + this.Text);
base.OnSelectedIndexChanged(e);
}
#endregion
#region OnDropDownClosed
protected override void OnDropDownClosed(EventArgs e)
{
Console.WriteLine("OnDropDownClosed " +
this.SelectedIndex + " " + this.Text);
base.OnDropDownClosed(e);
}
#endregion
}
控制台输出如下所示(选择项目:0,按Enter键时尝试更改为2,关闭DropDown索引后仍为0):
OnSelectedIndexChanged 0 item0
OnSelectedIndexChanged 2 item2
ENTER - 在DroppedDown = false 2 item2之前
OnDropDownClosed 0 item2
ENTER - 在DroppedDown = false 0 item2
之后
答案 0 :(得分:1)
protected override void OnDropDownClosed(EventArgs e)
{
Console.WriteLine("OnDropDownClosed " +
this.SelectedIndex + " " + this.Text);
int idx = this.SelectedIndex;
base.OnDropDownClosed(e);
this.SelectedIndex = idx;
}
答案 1 :(得分:0)
我发现设置SelectedItem比设置SelectedIndex更可靠。
//这也会改变SelectedIndex并触发SelectedItemChanged事件。
this.SelectedItem = this.Items [idx];