tags:

views:

520

answers:

2

In my WPF app (csharp) I have an event handler that when triggered will open a new window (window B) of the application and display some data. However, when the event is triggered again, if the new window (window B) is still open, I don't want to spawn another instance of window B but just update the data being displayed in the current instance. So the question is: How to detect if window B is already and only open if it is not already, otherwise just update the data?

I found the Application.Current.Window collection but somehow that isn't working for me yet. Ideas?

A: 

edit: oops, my answer is specific to Windows Forms. i just now saw the WPF mention. i'm not sure what the specific code would be for WPF, but i would imagine that it's not all that different conceptually. I think in WPF the property is called IsVisible instead of Visible

You could hold on to the instance of your window (or make it a Singleton) and then when you need to determine if it is visible or not, check it's Visible property.

for example:

if(myWindow.Visible){
  myWindow.Hide();
}else{
  myWindow.Show();
}
Brien W.
+2  A: 

You could create a LoadWindow() method in WindowB that you can call to load (or refresh) the data & that will work regardless of if the window is already open or not. Have it take a delegate to call when this window gets closed:

private Action ParentCallbackOnClose;

public void LoadWindow( Action parentCallbackOnClose ) {
    // load the data (set the DataContext or whatever)

    ParentCallbackOnClose = parentCallbackOnClose;    

    // Open the window and activate/bring to the foreground
    Show( );
    Activate( ); 
}

and have your window closed event call the close delegate:

private void WindowClosed( object sender, EventArgs e ) {
     ParentCallbackOnClose.Invoke( );
}

Now, from your class that opens Window B, have it hold onto that instance it opens, so that if WindowB is already open when someone tries to reload it, it just calls LoadWindow on the existing instance. Something like...

private WindowB WinB;

private void LoadWindowB(Content content)
{
    if (WinB == null ){
     WinB = new WindowB( );
    }
    WinB.LoadWindow(content, WindowBClosed);
}

And then you can just have it null out WinB on that close callback so if WinB is closed, then the next time LoadWindowB() is called it will create a new instance of it:

private void WindowBClosed( ){
    WinB = null;
}
Abby Fichtner