简体   繁体   English

在C#WPF中从前台表单关闭背景表单

[英]Closing background form from foreground form in C# wpf

I have the following task . 我有以下任务。

Steps : 脚步 :

Form A opens form B on click of button 点击按钮,表格A打开表格B

Expected : 预期:

Form B started and Form A closes . 表格B开始,表格A关闭。

Result : 结果:

Form B starts but Form A remains in the background . 表格B开始但表格A保留在背景中。

I tried to solve the problem by passing a reference of the Form A to Form B but it strangely does not work . 我试图通过将Form A的引用传递给Form B来解决此问题,但奇怪的是它不起作用。

In Form A :( MainWindow) Form A :( MainWindow)

 AdminWindow window = new AdminWindow();
 window.setCreatingForm = this;
 window.Show();

In Form B : (AdminWindow) Form B(AdminWindow)

public Window setCreatingForm
{
    get { return creatingForm; }
    set { creatingForm = value; }
}

public Window creatingForm { get; set; }

private void logOutClick(object sender, RoutedEventArgs e)
{
    if (creatingForm != null)
        creatingForm.Close(); `// Why does this not close the background Form` 
    MainWindow window = new MainWindow();
    window.Show();
}

I don't have much experience with WPF, but based on the one from Windows Forms, I think it would be easiest to close form A immediately after starting form B: 我没有使用WPF的丰富经验,但是基于Windows窗体的经验,我认为在启动窗体B之后立即关闭窗体A是最容易的:

// form A code for launching B
AdminWindow window = new AdminWindow();
window.setCreatingForm = this;
window.Show();
this.Close();

The above should work because the method launching form B does not quit or block after the call to window.Show(). 上面的方法应该起作用,因为启动window B的方法在调用window.Show()之后不会退出或阻塞。 The call only blocks if a modal window is displayed (which in Widows Forms is done with window.ShowDialog()). 仅在显示模式窗口时该调用才会阻塞(在Widows Forms中是通过window.ShowDialog()完成的)。

As for why the Close() in your code does not work, it looks like after destroying form A you are creating and showing a new form of the same type and maybe the original form is closed but what you are seeing is the newly created one. 至于为什么代码中的Close()无法正常工作,在销毁窗体A之后,您似乎正在创建并显示相同类型的新窗体,也许原始窗体已关闭,但是您看到的是新创建的窗体。

PS: It is a bad practice to include set or get in the name of .Net properties. PS:以.Net属性的名称包含set或get是一个不好的做法。 The set and get behavior are added by defining the set and get methods for the property. 通过定义属性的set和get方法来添加set和get行为。 So in your code for AdminWindow the property for the creating form should be named CreatingForm instead of setCreatingForm . 因此,在您为AdminWindow属性为创建表单代码应该被命名为CreatingForm代替setCreatingForm

Set the visible property of the parent form to false. 将父窗体的visible属性设置为false。

        public Form1()
        {
            InitializeComponent();          
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var form = new Form2();
            form.Show();
            this.Visible = false;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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