我正在开发一个 Windows 应用程序,其中包含一个 ListView ,其中包含许多项目。当用户单击项目时,应用程序会显示项目的详细信息。用户随后有机会编辑这些详细信息。每次更改后,用户都应该单击“保存”按钮,但是这并不总是发生。
如果用户进行更改而没有单击保存,则应用程序将显示一个消息框,询问他们是否想要保存更改。此框包括一个“取消”按钮,如果他们单击取消,我希望中止选择其他项目,并使用户保留在他们正在编辑的项目上。
我找不到方法来实现这一点。如果用户更改选项并且不保存,则从 itemselecedchanged 事件中显示对话框。如果用户单击取消,则我从事件中删除我的函数并手动更改所选项目,之后我将函数返回到事件中。但是之后事件被调用,手动选择的项目未被选中。
如果用户进行更改而没有单击保存,则应用程序将显示一个消息框,询问他们是否想要保存更改。此框包括一个“取消”按钮,如果他们单击取消,我希望中止选择其他项目,并使用户保留在他们正在编辑的项目上。
我找不到方法来实现这一点。如果用户更改选项并且不保存,则从 itemselecedchanged 事件中显示对话框。如果用户单击取消,则我从事件中删除我的函数并手动更改所选项目,之后我将函数返回到事件中。但是之后事件被调用,手动选择的项目未被选中。
private bool EnsureSelected()
{
bool continue_ = true;
if (_objectChange)
{
var res = MessageBox.Show("Do you want to save changes?", "Warning", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
switch (res)
{
case DialogResult.Cancel:
if (!string.IsNullOrEmpty(_selectedKey))
{
listView_Keys.ItemSelectionChanged -= listView_Keys_ItemSelectionChanged;
listView_Keys.Focus();
listView_Keys.Items[_selectedKey].Selected = true;
listView_Keys.ItemSelectionChanged += listView_Keys_ItemSelectionChanged;
}
continue_ = false;
break;
case DialogResult.Yes:
button_Save.PerformClick();
_objectChange = false;
break;
case DialogResult.No:
_objectChange = false;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
return continue_;
}
更新:
我尝试了以下解决方案:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private ListViewItem currentSelection = null;
private bool pending_changes = false;
private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (e.Item == currentSelection)
{
// if the current Item gets unselected but there are pending changes
if (!e.IsSelected && pending_changes)
{
var res = MessageBox.Show("Do you want to save changes?", "Warning", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
switch (res)
{
case DialogResult.Cancel:
// we dont want to change the selected item, so keep it selected
e.Item.Selected = true;
break;
case DialogResult.Yes:
//button_Save.PerformClick();
pending_changes = false;
break;
case DialogResult.No:
pending_changes = false;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
else // not the selected button
{
if (!pending_changes && e.IsSelected)
{
// Item may be selected and we save it as the new current selection
currentSelection = e.Item;
}
else if (pending_changes && e.IsSelected)
{
// Item may not be enabled, because there are pending changes
e.Item.Selected = false;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
listView1.Items[0].Selected = true;
}
private void button1_Click(object sender, EventArgs e)
{
pending_changes = true;
}
}
但这并没有起作用,第一次待处理的更改为真时,消息框调用了两次,第二次什么都没有发生。