How can I not open the same wpf window twice in c #?

1

I have a base application but the secondary window should not open twice when I click on the menu.

This is my code:

private void MenuItem_Click(object sender, RoutedEventArgs e)   {

    Agregar_Vendedor ventana_agregar_vendedor = new Agregar_Vendedor();

    ventana_agregar_vendedor.Show();

}

I do not know how to make it not open if it is already created.

    
asked by Elias Kaizer 16.12.2016 в 05:19
source

3 answers

1

If you want to open a secondary window and you can not return to the main window unless you close this second window, you can try the ShowDialog method:

private void MenuItem_Click(object sender, RoutedEventArgs e)   {

    Agregar_Vendedor ventana_agregar_vendedor = new Agregar_Vendedor();

    ventana_agregar_vendedor.ShowDialog();

}

If not, what you can do is disable the menu that opens the window when it is displayed:

private void MenuItem_Click(object sender, RoutedEventArgs e)   {

    Agregar_Vendedor ventana_agregar_vendedor = new Agregar_Vendedor();

    ventana_agregar_vendedor.ShowDialog();

    MenuItem.IsEnabled = false;
}

What you should do next, is to activate MenuItem again when the second window closes.

    
answered by 16.12.2016 в 08:49
0

The response of @Jose Antonio Bautista seems to me the most simple and correct. Anyway, keep in mind that in WPF you can know which windows are active through the collection Application.Current.Windows . So, if for whatever reason you would not want to / could use the ShowDialog() method, before creating a new instance of Agregar_Vendedor you could look if it is not already in that collection.

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    if (Application.Current.Windows.OfType<Agregar_Vendedor>().Count() == 0)
    {
        Agregar_Vendedor ventana_agregar_vendedor = new Agregar_Vendedor();
        ventana_agregar_vendedor.Show();
    }
}
    
answered by 16.12.2016 в 10:03
0

Very simple, you can achieve it with this tip:

The first thing is to declare your window as a class variable, without initializing:

private Agregar_Vendedor ventana_agregar_vendedor;

Or as property if you wish, it's more elegant:

private Agregar_Vendedor _ventana_agregar_vendedor;
public Agregar_Vendedor Ventana_agregar_vendedor
{
    get { return _ventana_agregar_vendedor; }
    set { _ventana_agregar_vendedor = value; }
}

Then when you need to open it, you do it this way:

if (ventana_agregar_vendedor == null)
{
    ventana_agregar_vendedor = new Agregar_Vendedor();
    ventana_agregar_vendedor.Closed += (a, b) => ventana_agregar_vendedor = null;
    ventana_agregar_vendedor.Show();
}
else
{
    ventana_agregar_vendedor.Show();                    
}

And ready.

    
answered by 19.12.2016 в 04:32