wjtk4444
wjtk4444

Reputation: 47

Switching between windows with only one instance of them

I have a problem with switching between windows in WPF app. Ie. MainWindow has one textbox, and Window1 has a button that edits this textbox text.

When I want to abort edition and I close (this.hide) Window1 there opens a new instance of MainWindow with default textbox text. How to avoid this ?

MainWindow:

Window1 window = new Window1();

Button_click
{
window.Show();
this.Hide();
}

Window1:

MainWindow mw = new MainWindow();

Button_click
{
mw.Show();
this.Hide();
}

I also tried with:

Window1 window = null;

Button_click
   {
      if(window == null)
      {
      window = new Window1();
      window.Show();
      }
      else
         window.Visibility = Visibility.Visible;

   this.Visibility = Visibility.Hidden;
}

And similar in Window1 code, but it seems not to work too.

I've read all the threads with similar question but those solutions don't work for me.

Upvotes: 1

Views: 107

Answers (1)

MikeG
MikeG

Reputation: 545

MainWindow:

 private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
       var window1 = new Window1(this);
       window1.Show();
       Hide();
    }

Window1:

 private MainWindow _mainWindow;

    public Window1(MainWindow refMainWindow)
    {
        InitializeComponent();
        _mainWindow = refMainWindow;
    }

    private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        _mainWindow.TextBox1.Text = "Hi From Window 1";
        _mainWindow.Show();
        Hide();
    }

Upvotes: 1

Related Questions