C# 如何将通知窗口设置为显示在主窗口的顶部?
在我的解决方案中,我有一个包含MainWindow(也称为应用程序的主窗口)的项目。在同一解决方案的另一个项目中,我有一个聊天客户端用户控件,当用户收到新消息时,该控件会显示一个通知窗口 我希望我的通知窗口弹出在主窗口的顶部,无论主窗口出现在哪里。只要用户有一个监视器,下面的代码就可以工作,如果有多个监视器,则主窗口最大化。但是,如果最小化主窗口,则通知将显示在工作区域的右上角,而不是主窗口 我尝试了下面的每一个代码集(在ChatClient.xaml.cs中执行),但都没有成功C# 如何将通知窗口设置为显示在主窗口的顶部?,c#,wpf,C#,Wpf,在我的解决方案中,我有一个包含MainWindow(也称为应用程序的主窗口)的项目。在同一解决方案的另一个项目中,我有一个聊天客户端用户控件,当用户收到新消息时,该控件会显示一个通知窗口 我希望我的通知窗口弹出在主窗口的顶部,无论主窗口出现在哪里。只要用户有一个监视器,下面的代码就可以工作,如果有多个监视器,则主窗口最大化。但是,如果最小化主窗口,则通知将显示在工作区域的右上角,而不是主窗口 我尝试了下面的每一个代码集(在ChatClient.xaml.cs中执行),但都没有成功 private
private const double topOffset = 0;
private const double leftOffset = 300;
popNotification.Top = Application.Current.MainWindow.Top + topOffset;
popNotification.Left = Application.Current.MainWindow.Width - leftOffset;
或
如何使通知窗口始终显示在主窗口的顶部?我应该在MainWindow.xaml.cs中执行它吗?谢谢你的帮助
编辑
下面的代码也会导致我的应用程序(通过MainWindow)崩溃。据我所知,这将窗口所有者设置为用户控件,而不是主窗口。我需要做什么呢
popNotification.Owner = Window.GetWindow(this);
我也试过:
popNotification.Owner = Window.GetWindow(Application.Current.MainWindow);
您需要将自定义窗口设置为打开
CenterOwner
,然后像这样设置窗口所有者
TestWindow window = new TestWindow();
window.Owner = Window.GetWindow(this);
window.ShowDialog();
我通过以下方法找到了答案:
- 使用@AlanLe on的答案中的代码
- 结合以上@jugg1es答案
public partial class ChatControl : User Control
{
PopNotifications popNotification = new PopNotifications();
--and other code
}
public ChatControl()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(ChatControl _Loaded);
}
private void ChatControl _Loaded(object sender, RoutedEventArgs e)
{
Window parentWindow = Window.GetWindow(this);
popNotification.Owner = parentWindow;
popNotification.Top = popNotification .Owner.Top;
popNotification.Left = popNotification .Owner.Left;
popNotification.WindowStartupLocation = WindowStartupLocation.Manual;
}
这并不完美,但它是可行的,而且比以前好多了。我没有打开的“对话框”。我试图在我的用户控件中引用MainWindow,类似于本文:;请参见上面的编辑。
public partial class ChatControl : User Control
{
PopNotifications popNotification = new PopNotifications();
--and other code
}
public ChatControl()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(ChatControl _Loaded);
}
private void ChatControl _Loaded(object sender, RoutedEventArgs e)
{
Window parentWindow = Window.GetWindow(this);
popNotification.Owner = parentWindow;
popNotification.Top = popNotification .Owner.Top;
popNotification.Left = popNotification .Owner.Left;
popNotification.WindowStartupLocation = WindowStartupLocation.Manual;
}