如何在WPF中优雅地更改切换按钮状态之前如何处理确认对话框?

问题描述 投票:0回答:1

说我有一个名为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对话框将不断弹出弹出窗口。

所以我该如何优雅地处理此案?

wpf button dialog toggle
1个回答
0
投票

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;
  }
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.