我只是创建自己的AboutBox,我使用Window.ShowDialog()
调用它如何让它相对于主窗口定位,即从顶部开始20px并居中。
感谢。
答案 0 :(得分:39)
您只需使用Window.Left和Window.Top属性即可。从主窗口读取它们并将值(加上20像素或其他)分配给AboutBox ,然后再调用ShowDialog()
方法。
AboutBox dialog = new AboutBox();
dialog.Top = mainWindow.Top + 20;
要使其居中,您还可以简单地使用WindowStartupLocation属性。将其设置为WindowStartupLocation.CenterOwner
AboutBox dialog = new AboutBox();
dialog.Owner = Application.Current.MainWindow; // We must also set the owner for this to work.
dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
如果你想让它水平居中,而不是垂直居中(即固定的垂直位置),你必须在加载AboutBox后在EventHandler中这样做,因为你需要根据宽度计算水平位置AboutBox,只有在加载后才知道。
protected override void OnInitialized(...)
{
this.Left = this.Owner.Left + (this.Owner.Width - this.ActualWidth) / 2;
this.Top = this.Owner.Top + 20;
}
gehho。
答案 1 :(得分:2)
我会采用手动方式,而不是指望WPF为我计算..
System.Windows.Point positionFromScreen = this.ABC.PointToScreen(new System.Windows.Point(0, 0));
PresentationSource source = PresentationSource.FromVisual(this);
System.Windows.Point targetPoints = source.CompositionTarget.TransformFromDevice.Transform(positionFromScreen);
AboutBox.Top = targetPoints.Y - this.ABC.ActualHeight + 15;
AboutBox.Left = targetPoints.X - 55;
其中ABC
是父窗口中的一些UIElement(如果你愿意,可以是所有者......),也可以是窗口本身(左上角)..