我想将模式对话框(进度窗口)放置在父窗口客户区的右上角。
这段代码会将其放在非客户区的角落,但是如何计算到客户区的偏移量?
this.Owner=owner;
this.Left=owner.Left+owner.ActualWidth-Width;
this.Top=owner.Top;
编辑:
我发现这个“解决方案”适用于普通窗口:
this.Left=owner.Left+owner.ActualWidth-Width-SystemParameters.ResizeFrameVerticalBorderWidth;
this.Top=owner.Top+SystemParameters.ResizeFrameHorizontalBorderHeight+SystemParameters.WindowCaptionHeight;
但是,对于具有自定义边框的窗口,这会失败。
编辑:
无论系统 DPI 设置如何(例如 120 而不是 96),代码都应该正常工作。
最佳答案
只要您的窗口内容是 UIElement 的子类(通常是这种情况),您就可以简单地检查内容覆盖的区域:
Matrix scaling = PresentationSource.FromVisual(windowContent)
.CompositionTarget.TransformFromDevice;
UIElement windowContent = owner.Content as UIElement;
Point upperRightRelativeToContent = new Point(
windowContent.RenderSize.Width + owner.Margin.Right,
-owner.Margin.Top);
Point upperRightRelativeToScreen =
windowContent.PointToScreen(upperRightRelativeToContent);
Point upperRightScaled =
scaling.Transform(upperRightRelativeToScreen);
this.Owner = owner;
this.Left = upperRightScaled.X - this.Width;
this.Top = upperRightScaled.Y;
如果您遇到奇怪的情况,希望它适用于任意 Window.Content
,则必须使用 VisualTreeHelper.GetChildCount()
搜索窗口的可视化树> 和 VisualTreeHelper.GetChild()
直到到达 ContentPresenter
,其 Content
属性与 Window
的属性匹配,并在上面的代码中使用它的第一个可视子元素作为“windowContent”。
关于c# - 如何计算 WPF 中客户区的偏移量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2026468/