如何从WPF中的子窗口获取数据?

时间:2015-12-01 10:03:19

标签: c# wpf

我有一个WPF应用程序,我在其中创建了一个代表自定义消息框的新窗口。它有两个按钮 - 是和否。

我从“父”表单中调用它,并希望收到答案,该答案应为"Yes""No",或truefalse

我正在尝试像Servy那样做:C# - Return variable from child window to parent window in WPF

但出于某种原因,我从未获得更新的值,因此isAllowed始终为假。

这是我父窗口中的代码:

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
}

然后在Child窗口中我有:

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();
}

1 个答案:

答案 0 :(得分:4)

在按钮单击事件处理程序中,首先需要设置DialogResult属性。像这样:

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

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

这将从ShowDialog方法返回,您只需将isAllowed变量分配给ShowDialog的结果。

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

if (isAllowed == true)
{
    ...