我可以订阅wpf中的某个事件来监听showDialog或新窗口吗?

时间:2016-09-19 17:16:12

标签: wpf

我想在我的应用中观察有关所有窗口的某些信息。我有一个窗口显示(通过Observables)很多信息,但我找不到任何简短的轮询,让我知道所有的窗口(以及我的应用程序中的所有打开的窗口)。

我可以订阅的某个地方对于任何显示的窗口(.Show().ShowDialog())都是一个很好的钩子吗?

1 个答案:

答案 0 :(得分:0)

您必须添加对UIAutomationClient.dllUIAutomationTypes.dll的引用。

在我的计算机上,它们位于C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5

CommonWindow用作您的公共窗口,不断更改其所有者。我创建了模态窗口,可以进一步创建更多的模态窗口,最新的一个 拥有 CommonWindow,我还将最新窗口设置为DataContext { {1}}。

CommonWindow

using System; using System.Windows; using System.Windows.Automation; using System.Threading; namespace WpfApplication1 { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { CommonWindow _commonWin = new CommonWindow(); private void Application_Startup(object sender, StartupEventArgs e) { Automation.AddAutomationEventHandler( WindowPattern.WindowOpenedEvent, AutomationElement.RootElement, TreeScope.Children, (s, e1) => { Application.Current.Dispatcher.Invoke(() => { var windows = Application.Current.Windows; Window w = windows[windows.Count - 1]; w.Closing += w_Closing; // First modal window is shown, so count now is 2 (>1) if (App.Current.Windows.Count > 1) { _commonWin.Owner = w; _commonWin.DataContext = w; _commonWin.Show(); } }); }); } void w_Closing(object sender, System.ComponentModel.CancelEventArgs e) { // Comparison to 3 is important as there would be 3 windows when first modal window is shown if (Application.Current.Windows.Count >= 3) { _commonWin.Owner = Application.Current.Windows[App.Current.Windows.Count - 2]; _commonWin.DataContext = Application.Current.Windows[App.Current.Windows.Count - 2]; } else { _commonWin.Close(); } } } } 只是CommonWindow Window,就像普通的xaml文件及其代码隐藏一样。

相关问题