在c#中使用来自两个不同父窗口的子窗口
本文关键字:窗口 两个 | 更新日期: 2023-09-27 18:06:49
我的问题涉及以下3个表单:
MainWindow.cs
SettingsWindow.cs
AuthenticationWindow.cs
设置窗口包含"是否在启动时询问密码"等信息。
我从设置窗口调用身份验证窗口,以便删除密码(当密码设置时)。
我也在启动期间调用身份验证窗口(当设置密码时)。
我的身份验证窗口使用一个静态变量与设置窗口交互(说明身份验证是否成功)。
但是,为了重用相同的代码(即,在启动期间调用相同的身份验证窗口),我无法告诉主窗口身份验证是否成功。但是,我必须设法重用这些代码。
我的问题是:是否有可能通知子窗口关于父窗口是谁?如果是,请提供示例代码…
希望我的问题很清楚。
请帮忙!
我假设Authentication Window与ShowDialog()一起使用,如下所示:
AuthenticationWindow auth = new AuthenticationWindow();
if (auth.ShowDialog(this) == DialogResult.Ok)
{
// we know it was successful
}
然后在AuthenticationWindow
中,当您成功时,您将调用:
DialogResult = DialogResult.Ok;
Close();
来获得上面的反馈,或者通过
表示失败 DialogResult = DialogResult.Cancel;
Close();
或者,您可以在AuthenticationWindow上设置一个属性:
class AuthenticationWindow : Form
{
public bool Success { get; set;}
}
,并在AuthenticationWindow代码中适当地设置Success的值。
最后,如果您希望将即时反馈发送到其他窗口,请考虑实现一个事件:
class AuthenticationWindow : Form
{
public event Action<bool> SignalOutcome;
private OnSignalOutcome(bool result)
{
Action<bool> handler = SignalOutCome;
if (handler != null) handler(result);
}
}
那么您必须订阅调用身份验证窗口的事件:
AuthenticationWindow auth = new AuthenticationWindow();
auth.SignalOutcome += (outcome) => { /* do something with outcome here */ };
auth.ShowDialog(this);
ChildWindow c1=new ChildWindow();
c1.Owener=authenticationWindow;
c1.Show(); //or ShowDialog();
ChildWindow c2=new ChildWindow();
c1.Owener=anotherWindow;
c2.Show(); //or ShowDialog();
//to get the parent, use the property c.Owner
if(c.Owner is AuthenticationWindow) //AuthenticationWindow is the type of authenticationWindow instance
{
...
}