说我有一个名为btn1
的切换按钮,当未选中状态时显示Open
,在选中状态时显示Close
。我定义了两个函数来简单地处理它的已检查/未检查事件:
private void Btn_Checked(object sender, RoutedEventArgs e)
{
// Do some open operation.
}
和
private void Btn_Unchecked(object sender, RoutedEventArgs e)
{
// Do some close operation.
}
现在,我想在用户单击切换按钮时显示一个确认对话框。因此,我在do some open/close operation
之前添加了一个MessageBox。代码变成
private void Btn_Checked(object sender, RoutedEventArgs e)
{
MessageBoxResult res = MessageBox.Show("Do you really want to open it?", "app name", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
if(res == MessageBoxResult.OK)
{
// Do some open operation.
}
else
{
btn1.IsChecked = false;
}
}
未检查的处理程序类似于已检查的处理程序。
但是运行这些代码后,如果选择取消对话框,则checked
/ unchecked
对话框将不断弹出弹出窗口。
所以我该如何优雅地处理此案?
Yahey!我找到了解决方案,但可能并不优雅。
private void Btn_Checked(object sender, RoutedEventArgs e)
{
if(btn1.Tag != null)
{
btn1.Tag = null;
return;
}
MessageBoxResult res = MessageBox.Show("Do you really want to open it?", "app name", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
if(res == MessageBoxResult.OK)
{
// Do some open operation.
}
else
{
btn1.Tag = "ignore";
btn1.IsChecked = false;
}
}
private void Btn_Unchecked(object sender, RoutedEventArgs e)
{
if(btn1.Tag != null)
{
btn1.Tag = null;
return;
}
MessageBoxResult res = MessageBox.Show("Do you really want to close it?", "app name", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
if(res == MessageBoxResult.OK)
{
// Do some close operation.
}
else
{
btn1.Tag = "ignore";
btn1.IsChecked = true;
}
}