我决定在 WPF 中创建自己的对话框窗口。我让它使用框架工作并导航到框架中的 WPF 页面以获取我之前制作的相应对话框窗口。当尝试返回值时就会出现问题。例如,如果我有“确定”和“取消”,我希望在框架中显示的页面上按“确定”或“取消”时返回 bool 值。
//This is what I'm using to display the dialog window frame.
public bool DisplayQuestion(string subject, string message)
{
AlertIsUp = true;
var questionPage = new QuestionPage(AlertFrame, subject, message);
AlertFrame.Navigate(questionPage);
if (MainFrame.Content != null && MainFrame.Content.ToString() == "System.Windows.Controls.WebBrowser")
{
MainFrame.Visibility = System.Windows.Visibility.Hidden;
}
//I need it to wait until a button on the dialog frame is pressed before continuing.
return QuestionResponse;
}
发生的情况是,它将立即返回 bool 值,当然该值始终为 false。我需要它等到页面中按下“确定”或“取消”,然后继续返回它的值。
这是页面内的代码。
Frame AlertFrame { get; set; }
public bool AlertIsUp { get; set; }
public bool QuestionResponse { get; set; }
public QuestionPage(Frame alertFrame, string subject, string message)
{
InitializeComponent();
theMesssage.Content = message;
subjectLabel.Content = subject;
AlertFrame = alertFrame;
AlertIsUp = MainWindow.AlertIsUp;
QuestionResponse = MainWindow.QuestionResponse;
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
AlertFrame.Content = null;
AlertIsUp = false;
QuestionResponse = false;
}
private void OkButton_Click(object sender, RoutedEventArgs e)
{
AlertFrame.Content = null;
AlertIsUp = false;
QuestionResponse = true;
}
当然,如果我只是添加 While(AlertIsUp) 那么 if 会卡住 GUI。 由于我没有接受过任何正式的 C# 培训,所以我很可能做事落后。感谢您对我在本网站上的第一篇文章的友好回复。
最佳答案
我实际上在这里找到了解决这个问题的方法:
http://www.codeproject.com/Articles/36516/WPF-Modal-Dialog
解决方案最终放置了这段简短的代码:
while (AlertIsActive)
{
if (this.Dispatcher.HasShutdownStarted ||
this.Dispatcher.HasShutdownFinished)
{
break;
}
this.Dispatcher.Invoke(
DispatcherPriority.Background,
new ThreadStart(delegate { }));
Thread.Sleep(20);
}
关于C# WPF 暂停处理直到按下按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25653326/