gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:03:55 37 4
gpt4 key购买 nike

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

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com