Just a user
Just a user

Reputation: 629

XAML C# - Opening Windows

I am starting XAML coding and cannot for the life of it find out if a window is openen or not (once openen by clicking a button)

For now, it keeps opening unlimited amounts of windows. What I want is that once a window is openen, it won't open again, even if you press the button again.

here's my code, but with this it's not showing a window at all! What am i doing wrong?

    private void System_Agents(object sender, RoutedEventArgs e)
    {
        var newW = new SystemAgents();

        if ( newW == null )
        {
            newW.Show();
        }
        else newW.Activate();

Upvotes: 0

Views: 50

Answers (2)

Just a user
Just a user

Reputation: 629

I solved it! After long searching, it was actually quite easy!

Here's the code:

 SystemAgents window; //Presets a variable to SystemAgents window
    private void System_Agents(object sender, RoutedEventArgs e) //Call method
    {

        if ( window == null )
        {
            window = new SystemAgents(); //Sets variable "window" to the window "SystemAgents"
            window.Show(); //Shows the window "System Agents"
            window.Owner = this; //Determins the owner of the window is the main Application
            window.Closed += new EventHandler(AddItemView_Closed); //Sets a new method (defined below) to what happens if you close the window so window will close when app closes.
        }
        else window.Activate(); //Will set the window as active.
        //newW.ShowDialog();  //Will Show Window, but unable to do anything else other then the window

    }
    void AddItemView_Closed(object sender, EventArgs e)
    {
            window = null;
    }

Upvotes: 0

adv12
adv12

Reputation: 8551

When you create the window the first time, store the newly-created window instance in a member variable of the class that creates it. Then check that member variable before creating it the next time you want that window, and if it's not null, don't create another.

Upvotes: 2

Related Questions