如何在WPF的Page.xaml中设置窗口Topmost为true?代码失效求助
在WPF Page中设置窗口Topmost属性的正确方法
你的代码无效的核心原因是:你新建了一个MainWindows实例ui,但这个实例并不是当前承载Page的那个正在显示的窗口,所以修改它的Topmost属性不会对实际显示的窗口产生任何影响,和Page本身没有关系。
以下是两种可行的修复方案:
方案一:获取当前Page所在的窗口实例
通过Window.GetWindow(this)方法可以直接获取到当前Page所属的窗口,然后修改它的Topmost属性:
private void TopMostCheckBox_Checked(object sender, RoutedEventArgs e) { var currentWindow = Window.GetWindow(this); if (currentWindow != null) { currentWindow.Topmost = true; } }
如果需要处理取消勾选的情况,可以同时实现Unchecked事件:
private void TopMostCheckBox_Unchecked(object sender, RoutedEventArgs e) { var currentWindow = Window.GetWindow(this); if (currentWindow != null) { currentWindow.Topmost = false; } }
方案二:通过应用程序获取主窗口实例
如果你的主窗口是应用程序的主窗口(即Application.Current.MainWindow指向的窗口),也可以直接通过这个属性获取并修改:
private void TopMostCheckBox_Checked(object sender, RoutedEventArgs e) { if (Application.Current.MainWindow != null) { Application.Current.MainWindow.Topmost = true; } }
同样,取消勾选的处理类似:
private void TopMostCheckBox_Unchecked(object sender, RoutedEventArgs e) { if (Application.Current.MainWindow != null) { Application.Current.MainWindow.Topmost = false; } }
更简洁的写法(合并事件)
也可以将勾选和取消勾选的逻辑合并到一个事件中,比如使用Click事件:
private void TopMostCheckBox_Click(object sender, RoutedEventArgs e) { var checkBox = sender as CheckBox; var targetWindow = Window.GetWindow(this); if (checkBox != null && targetWindow != null) { targetWindow.Topmost = checkBox.IsChecked == true; } }
内容的提问来源于stack exchange,提问作者me_d
相关产品推荐
相关产品推荐

