C# WPF 暂停处理直到按下按钮

标签 c# wpf dialog wait

我决定在 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/

相关文章:

wpf - WPF 字体中不可预测的不透明度行为

wpf - 哪里有关于如何在 WPF 应用程序中将 Caliburn.Micro MVVM 与 Entity Framework 结合起来的说明?

c++ - 将值从主窗口更新到对话框

java - 如何在 Dialog dismiss Android 上触发事件?

java - 如何创建一个自定义alertDialog,其中的列表绑定(bind)到onClick事件android?

c# - 牛顿软件.Json.JsonReaderException : Additional text encountered after finished reading JSON content:

c# - WPF ListView 选择问题

wpf - WPF TextBlock 和 TextBox 有什么区别吗?

c# - 在 Literals 中加载 javascript 文件是一种不好的做法吗? (ASP.NET)

c# - .NET WCF w3wp native 内存泄漏和加载程序堆中 0 大小的 18k 动态程序集