【发布时间】:2016-06-20 07:53:03
【问题描述】:
我很惊讶我以前没有注意到这一点,并且在任何地方都找不到这个问题。也许我错过了一些明显的东西。当我将ComboBox 的DataSource 设置为BindingList 并从列表中删除一个项目时,SelectedValueChanged 或SelectedIndexChanged 事件不会被触发,但 SelectedValue 会发生变化。以下是要复制的完整来源:
public partial class Form1 : Form
{
public readonly BindingList<string> Items = new BindingList<string>();
public Form1()
{
InitializeComponent();
Items.Add("One");
Items.Add("Two");
Items.Add("Three");
comboBox1.DataSource = Items;
comboBox1.SelectedValueChanged += comboBox1_SelectedValueChanged;
comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
button1.Click += button1_Click;
timer1.Interval = 250;
timer1.Tick += timer1_Tick;
timer1.Start();
}
private string GetCurrentText()
{
return comboBox1.SelectedValue as string ?? "NULL";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text += "Index Changed: " + GetCurrentText() + Environment.NewLine;
}
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
textBox1.Text += "Value Changed: " + GetCurrentText() + Environment.NewLine;
}
private void timer1_Tick(object sender, EventArgs e)
{
Text = GetCurrentText();
}
private void button1_Click(object sender, EventArgs e)
{
Items.Remove((string)comboBox1.SelectedValue);
}
}
所有表单都有一个ComboBox、一个Button、一个Timer 来跟踪实际的ComboBox 的SelectedValue 和一个多行TextBox 来记录事件。
要重现,请运行表单,从组合框中选择第二个值(“Two”),然后按下按钮。按下按钮时不会触发SelectedValueChanged 或SelectedIndexChanged 事件,但表单的文本将显示计时器给出的新值(“三”),这也将是组合框中显示的值。因此,实际选择的值肯定会发生变化,不会触发任何事件。
不幸的是,没有SelectedItemChanged 事件,所以我不知道开发人员应该如何处理这种情况。我不确定哪些其他“边缘”案例会导致价值无声地改变,所以我想出的任何 hacky 解决方案都可能无法涵盖所有案例。我想知道是否有人提出了真正的解决方案。
【问题讨论】:
-
所有事件都完美运行。按钮事件已触发。我刚刚复制并粘贴了您的代码。
-
@TripleK 你有没有使用过.NET 4.5以外的任何东西?
-
@TripleK I ment selected...更改了事件(刚刚编辑)
-
@TripleK 我尝试编辑上面的评论以避免垃圾邮件,但为时已晚。我认为您误解并测试了 buttonclick 事件,而不是任何组合框的 selected...changed 事件。如果是这样,很抱歉造成混淆,只需编辑问题以使其清楚。