简体   繁体   中英

How to get data from child window in WPF?

I have a WPF application, where I have created a new window that represents a custom message box. It has two buttons - yes and no.

I am calling it from the Parent form and expect to receive the answer, which should be "Yes" or "No" , or true or false .

I am trying to do the same as Servy 's asnwer here: C# - Return variable from child window to parent window in WPF

But for some reason, I never get the updated value, so isAllowed is always false.

This is the code in my Parent window:

bool isAllowed = false;

ChildMessageBox cmb = new ChildMessageBox();
cmb.Owner = this;
cmb.Allowed += value => isAllowed = value;
cmb.ShowDialog();

if (isAllowed) // it is always false
{
    // do something here
}

And then in the Child window I have:

public event Action<bool> Allowed;

public ChildMessageBox()
{
     InitializeComponent();
}

private void no_button_Click(object sender, RoutedEventArgs e)
{
     Allowed(false);
     this.Close();
}

private void yes_button_Click(object sender, RoutedEventArgs e)
{
     Allowed(true); // This is called when the Yes button is pressed
     this.Close();
}

In your button click event handlers, you first need to set the DialogResult property. Like this:

private void no_button_Click(object sender, RoutedEventArgs e)
{
    DialogResult = false;
    Close();
}

//Do the same for the yes button (set DialogResult to true)
...

This will be returned from the ShowDialog method, you can simply assign your isAllowed variable to the result of ShowDialog .

bool? isAllowed = false;
...
isAllowed = cmb.ShowDialog();

if (isAllowed == true)
{
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM