单击按钮时通知主线程

时间:2013-01-09 10:51:34

标签: c# windows-runtime .net-4.5

我正在尝试像这样创建一个Popup

// 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事件时nofify主线程,所以我可以继续该线程

但我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

我将假设您正在询问如何实现类似行为的对话,类似于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's Flyout控件以获得更简单的方法来实现弹出窗口。

答案 1 :(得分:0)

在类的内部和事件内部放置一个布尔属性,将布尔值设置为true。

ButtonFill.Click += (sender, e) => { ButtonClicked = true; Obj.Value = TxtBoxValue.Text; };