Reputation: 2180
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();
}
Upvotes: 0
Views: 685
Reputation: 9723
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)
{
...
Upvotes: 4