Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close a Window from Another In Wpf

Tags:

wpf

c#-4.0

If two Window is opened mainly A and B, how to close Window A using code that written on Window B.

like image 643
Anoop Mohan Avatar asked Jul 28 '12 04:07

Anoop Mohan


1 Answers

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.

Main Window

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

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

        }
    }
}

like image 64
Mark Hall Avatar answered Nov 03 '22 01:11

Mark Hall