且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Wpf中关闭另一个窗口

更新时间:2023-01-07 18:35:15

***的办法是在窗口B上创建一个属性,你传递创建窗口。这样的东西。我有一个名为MainWindow的窗口和名为Window2的第二个窗口。

Your best bet would be to create a property on Window B that you pass the creating Window to. Something like this. I have a Window named MainWindow and a second Window named Window2.

主窗口

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Window2 secondForm;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            secondForm = new Window2();
            secondForm.setCreatingForm =this;
            secondForm.Show();
        }
    }
}

strong>

Window2

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for Window2.xaml
    /// </summary>
    public partial class Window2 : Window
    {
        Window creatingForm;

        public Window2()
        {
            InitializeComponent();
        }

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

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (creatingForm != null)
                creatingForm.Close();

        }

    }
}





重新填写您的评论,关闭由另一个表单创建的窗口与调用创建表单的关闭方法一样简单:


In respose to your comment, closing a window that was created by another form is as easy as calling the Close Method of the created Form:

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Window2 secondForm;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (secondForm == null)
            {
                secondForm = new Window2();
                secondForm.Show();
            }
            else
                secondForm.Activate();
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            if (secondForm != null)
            {
                secondForm.Close();
                secondForm = new Window2();
                //How ever you are passing information to the secondWindow
                secondForm.Show();
            }

        }
    }
}