WPF Modal Window using ShowDialog() Blocks All Other Windows

前端 未结 2 635
梦如初夏
梦如初夏 2020-12-24 07:18

My application has several independent \"top-level\" windows, which all have completely different functions/workflows.

I am currently using ShowDialog() to make a WP

2条回答
  •  渐次进展
    2020-12-24 07:57

    One option is to start the windows that you don't want affected by the dialog on a different thread. This may result in other issues for your application, but if those windows do really encapsulate different workflows, that may not be an issue. Here is some sample code I wrote to verify that this works:

    
        
            
            

    using System.ComponentModel;
    using System.Threading;
    using System.Windows;
    
    namespace ModalSample
    {
        /// 
        /// Interaction logic for MyWindow.xaml
        /// 
        public partial class MyWindow : INotifyPropertyChanged
        {
            public MyWindow()
            {
                InitializeComponent();
                DataContext = this;
            }
    
            private int child = 1;
    
            private string mIdentifier = "Root";
            public string Identifier
            {
                get { return mIdentifier; }
                set
                {
                    if (mIdentifier == value) return;
                    mIdentifier = value;
                    if (PropertyChanged != null)
                        PropertyChanged(this, new PropertyChangedEventArgs("Identifier"));
                }
            }
    
            private void OpenNormal_Click(object sender, RoutedEventArgs e)
            {
                var window = new MyWindow {Identifier = Identifier + "-N" + child++};
                window.Show();
            }
    
            private void OpenIndependent_Click(object sender, RoutedEventArgs e)
            {
                var thread = new Thread(() =>
                    {
                        var window = new MyWindow {Identifier = Identifier + "-I" + child++};
                        window.Show();
    
                        window.Closed += (sender2, e2) => window.Dispatcher.InvokeShutdown();
    
                        System.Windows.Threading.Dispatcher.Run();
                    });
    
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
            }
    
            private void OpenModal_Click(object sender, RoutedEventArgs e)
            {
                var window = new MyWindow { Identifier = Identifier + "-M" + child++ };
                window.ShowDialog();
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
        }
    }
    

    I sourced this blog post for running a WPF window on a different thread.

提交回复
热议问题