使用ShowDialog()的WPF模态窗口阻止所有其他Windows

时间:2010-04-07 15:00:04

标签: wpf

我的应用程序有几个独立的“顶级”窗口,它们都具有完全不同的功能/工作流程。

我目前正在使用ShowDialog()来制作WPF窗口模式。模态窗口是其中一个主窗口的子窗口。但是,它一旦打开就会阻止所有顶级窗口。我希望该对话框仅阻止它从中启动的父窗口。这可能吗?

我不确定它是否重要,但打开对话框的窗口是应用程序的初始窗口 - 所以所有其他顶级窗口都是从它打开的。

2 个答案:

答案 0 :(得分:11)

一个选项是在不同的线程上启动您不希望受对话框影响的窗口。这可能会导致您的应用程序出现其他问题,但如果这些窗口确实封装了不同的工作流程,那么这可能不是问题。下面是我编写的一些示例代码,用于验证这是否有效:

<Window x:Class="ModalSample.MyWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="{Binding Identifier}" Height="150" Width="150">
    <StackPanel>
        <TextBox Text="{Binding Identifier}" />
        <Button Content="Open Normal Child" Click="OpenNormal_Click" />
        <Button Content="Open Independent Child" Click="OpenIndependent_Click" />
        <Button Content="Open Modal Child" Click="OpenModal_Click" />
    </StackPanel>
</Window>

using System.ComponentModel;
using System.Threading;
using System.Windows;

namespace ModalSample
{
    /// <summary>
    /// Interaction logic for MyWindow.xaml
    /// </summary>
    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;
    }
}

我找到了this blog post来在不同的线程上运行WPF窗口。

答案 1 :(得分:7)

我遇到了同样的问题并实现了这篇文章中描述的模态对话框行为: http://social.msdn.microsoft.com/Forums/vstudio/en-US/820bf10f-3eaf-43a8-b5ef-b83b2394342c/windowsshowmodal-to-parentowner-window-only-not-entire-application?forum=wpf

我还尝试了多UI线程方法,但这会导致第三方库(caliburn micro&amp; telerik wpf控件)出现问题,因为它们不是为在多个UI线程中使用而构建的。可以使它们使用多个UI线程,但我更喜欢更简单的解决方案...

如果按照描述实现对话框,则不能再使用DialogResult属性,因为它会导致“只有在创建Window并显示为对话框”异常后才能设置“DialogResult”。只需实现自己的属性并使用它。

您需要以下Windows API参考:

/// <summary>
/// Enables or disables mouse and keyboard input to the specified window or control. 
/// When input is disabled, the window does not receive input such as mouse clicks and key presses. 
/// When input is enabled, the window receives all input.
/// </summary>
/// <param name="hWnd"></param>
/// <param name="bEnable"></param>
/// <returns></returns>
[DllImport("user32.dll")]
private static extern bool EnableWindow(IntPtr hWnd, bool bEnable);

然后使用:

// get parent window handle
IntPtr parentHandle = (new WindowInteropHelper(window.Owner)).Handle;
// disable parent window
EnableWindow(parentHandle, false);
// when the dialog is closing we want to re-enable the parent
window.Closing += SpecialDialogWindow_Closing;
// wait for the dialog window to be closed
new ShowAndWaitHelper(window).ShowAndWait();
window.Owner.Activate();

这是在关闭对话框时重新启用父窗口的事件处理程序:

private void SpecialDialogWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    var win = (Window)sender;
    win.Closing -= SpecialDialogWindow_Closing;
    IntPtr winHandle = (new WindowInteropHelper(win)).Handle;
    EnableWindow(winHandle, false);

    if (win.Owner != null)
    {
        IntPtr parentHandle = (new WindowInteropHelper(win.Owner)).Handle;
        // reenable parent window
        EnableWindow(parentHandle, true);
    }
}

这是实现模式对话行为所需的ShowAndWaitHelper(这会阻止线程的执行,但仍会执行消息循环。

private sealed class ShowAndWaitHelper
{
    private readonly Window _window;
    private DispatcherFrame _dispatcherFrame;
    internal ShowAndWaitHelper(Window window)
    {
        if (window == null)
        {
            throw new ArgumentNullException("window");
        }
        _window = window;
    }
    internal void ShowAndWait()
    {
        if (_dispatcherFrame != null)
        {
            throw new InvalidOperationException("Cannot call ShowAndWait while waiting for a previous call to ShowAndWait to return.");
        }
        _window.Closed += OnWindowClosed;
        _window.Show();
        _dispatcherFrame = new DispatcherFrame();
        Dispatcher.PushFrame(_dispatcherFrame);
    }
    private void OnWindowClosed(object source, EventArgs eventArgs)
    {
        if (_dispatcherFrame == null)
        {
            return;
        }
        _window.Closed -= OnWindowClosed;
        _dispatcherFrame.Continue = false;
        _dispatcherFrame = null;
    }
}