将WindowStartupLocation设置为边距.主窗口Button1的顶部

本文关键字:窗口 Button1 顶部 WindowStartupLocation 设置 | 更新日期: 2023-09-27 18:13:54

我正在做一个项目,当用户将按钮悬停在主窗口时,我必须添加一个小预览窗格和一个about框。

举个例子:我有一个窗口预览。我的主窗口叫做MainWindow.xaml.

如何设置预览窗口底部出现在主窗口上的button1的顶部?

我试过这样做,但没有任何运气:

public preview()
{
   InitializeComponent();
   this.WindowStartupLocation = WindowStartupLocation.Manual;
   Top = mainWindow.button1.Margin.Top;
}
我希望我的胡言乱语有意义…

任何帮助都非常感谢!

将WindowStartupLocation设置为边距.主窗口Button1的顶部

您需要将LeftTop窗口属性设置为屏幕坐标,按钮边距在这里不起作用。使用PointToScreen函数获取按钮的屏幕坐标:

    private void button1_MouseEnter(object sender, MouseEventArgs e)
    {
        var control = ((FrameworkElement)sender);
        // get screen coordinates of (0,0) point of button
        var location = control.PointToScreen(new Point(0, 0));
        var w = new preview()
        {
            WindowStartupLocation = System.Windows.WindowStartupLocation.Manual,
            ShowActivated = false,
        };
        w.Top = location.Y - w.Height;
        w.Left = location.X + (control.ActualWidth - w.Width) / 2;
        w.Show();
    }

你必须反过来做。在主窗口中打开预览窗口,执行如下操作:

PreviewWindow preview = new PreviewWindow
{
     Owner = this,
     WindowStartupLocation = WindowStartupLocation.Manual,
     Top = button1.Margin.Top
};
preview.Show();

如果你想重用那个窗口,你必须做一点逻辑。