Osk*_*lin 17
你无法取消它.
我几天前所做的就是拥有一个带有最新选定索引的变量.然后,当事件触发时,您询问用户是否要保存,这是在事件处理程序中完成的.如果用户选择"取消",则再次更改ID.
问题是,这将使事件再次发生.所以我使用的是一个bool只是说"抑制".在事件处理程序的顶部,我有:
if(Inhibit)
return;
Run Code Online (Sandbox Code Playgroud)
然后在这下面你提出问题,你做这样的事情:
DialogResult result = MessageBox.Show("yadadadad", yadada cancel etc);
if(result == DialogResult.Cancel){
Inhibit = true; //Make sure that the event does not fire again
list.SelectedIndex = LastSelectedIndex; //your variable
Inhibit = false; //Enable the event again
}
LastSelectedIndex = list.SelectedIndex; // Save latest index.
Run Code Online (Sandbox Code Playgroud)
这正是@Oskar Kjellin的方法,但有一点扭曲.也就是说,一个较小的变量和一个选定的索引改变了事件,它真的表现得像一个选定的索引改变了事件.我经常想知道为什么即使我点击完全相同的选定项目,选择索引更改事件也会被触发.在这里它没有.是的,这是一个偏差,所以要更加确定你是否希望它在那里.
int _selIndex = -1;
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex == _selIndex)
return;
if (MessageBox.Show("") == DialogResult.Cancel)
{
listBox1.SelectedIndex = _selIndex;
return;
}
_selIndex = listBox1.SelectedIndex;
// and the remaining part of the code, what needs to happen when selected index changed happens
}
Run Code Online (Sandbox Code Playgroud)
小智 6
我刚遇到这个问题.我做的是当用户进行更改时,我设置ListBox.Enabled = false; 这不允许他们选择不同的索引.一旦他们保存或放弃他们的更改,我设置ListBox.Enabled = true; 可能不像提示那样光滑,但它完成了工作.
小智 5
更优雅,使用 Tag 属性:
if ((int)comboBox.Tag == comboBox.SelectedIndex)
{
// Do Nothing
}
else
{
if (MessageBox.Show("") == DialogResult.Cancel)
{
comboBox.SelectedIndex = (int)comboBox.Tag;
}
else
{
// Reset the Tag
comboBox.Tag = comboBox.SelectedIndex;
// Do what you have to
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14943 次 |
| 最近记录: |