当按钮被点击时通知主线程
本文关键字:通知 线程 按钮 | 更新日期: 2023-09-27 17:51:14
我想创建一个像这样的弹出窗口
// Create a Popup
var Pop = new Popup() { IsOpen = true };
// Create a StackPanel for the Buttons
var SPanel = new StackPanel() { Background = MainGrid.Background };
// Set the comment
var TxtBlockComment = new TextBlock { Margin = new Thickness(20, 5, 20, 5), Text = Obj.Comment };
// Set the value
var TxtBoxValue = new TextBox { Name = "MeasureValue" };
TxtBoxValue.KeyUp += (sender, e) => { VerifyKeyUp(sender, Measure); };
// Create the button
var ButtonFill = new Button { Content = Loader.GetString("ButtonAccept"), Margin = new Thickness(20, 5, 20, 5), Style = (Style)App.Current.Resources["TextButtonStyle"] };
ButtonFill.Click += (sender, e) => { Obj.Value = TxtBoxValue.Text; };
// Add the items to the StackPanel
SPanel.Children.Add(TxtBlockComment);
SPanel.Children.Add(TxtBoxValue);
SPanel.Children.Add(ButtonFill);
// Set the child on the popup
Pop.Child = SPanel;
我想通知主线程,当ButtonFill.Click
事件已经执行,所以我可以继续这个线程
但是我怎么做呢?
我假设您在问如何实现类似于FileOpenPicker.PickSingleFileAsync
的对话框行为。您可以使用TaskCompletionSource
创建一个可等待任务:
private Task<string> OpenPopupAsync()
{
var taskSource = new TaskCompletionSource<string>();
// Create a Popup
var Pop = new Popup() { IsOpen = true };
// Create a StackPanel for the Buttons
var SPanel = new StackPanel() { Background = MainGrid.Background };
// Set the comment
var TxtBlockComment = new TextBlock { Margin = new Thickness(20, 5, 20, 5), Text = Obj.Comment };
// Set the value
var TxtBoxValue = new TextBox { Name = "MeasureValue" };
TxtBoxValue.KeyUp += (sender, e) => { VerifyKeyUp(sender, Measure); };
// Create the button
var ButtonFill = new Button { Content = Loader.GetString("ButtonAccept"), Margin = new Thickness(20, 5, 20, 5), Style = (Style)App.Current.Resources["TextButtonStyle"] };
ButtonFill.Click += (sender, e) => { Pop.IsOpen = false; taskSource.SetResult(TxtBoxValue.Text); };
// Add the items to the StackPanel
SPanel.Children.Add(TxtBlockComment);
SPanel.Children.Add(TxtBoxValue);
SPanel.Children.Add(ButtonFill);
// Set the child on the popup
Pop.Child = SPanel;
return taskSource.Task;
}
简而言之:- 创建
TaskCompletionSource
的实例 - 返回
Task
属性作为可等待任务 - 当您希望调用方法继续时,您可以调用
SetResult
在调用方法中,您只需在继续执行之前为方法返回await
:
string result = await OpenPopupAsync();
// continue execution after the method returns
我还建议你看看Callisto的Flyout控件,以更简单的方式实现弹出窗口。
为类设置一个布尔属性,并在开始的事件中设置该布尔值为true。
ButtonFill.Click += (sender, e) => { ButtonClicked = true; Obj.Value = TxtBoxValue.Text; };