wpfmvvmprism-4

How can I prevent WPF Window from opening if I have an already opened window ?


I have an opened window and I am using the .Show() method, I would like to prevent any other windows to be opened If I have an opened window. something else than ShowDialog().


Solution

  • Keep track of the number of open windows as you open them one way or another, .e.g.:

    public class WindowService
    {
        private const int MaxNumberOfOpenWindows = 1;
        private int _currentNumberOfOpenWindows = 0;
    
        public void OpenWindow()
        {
            if (_currentNumberOfOpenWindows != MaxNumberOfOpenWindows)
            {
                Window window = new Window();
                window.Closed += Window_Closed;
                window.Show();
                _currentNumberOfOpenWindows++;
            }
        }
    
        private void Window_Closed(object sender, EventArgs e)
        {
            Window window = (Window)sender;
            window.Closed -= Window_Closed;
            _currentNumberOfOpenWindows--;
        }
    }