c# - 如何计算 WPF 中客户区的偏移量?

标签 c# wpf user-interface

我想将模式对话框(进度窗口)放置在父窗口客户区的右上角。

这段代码会将其放在非客户区的角落,但是如何计算到客户区的偏移量?

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/

相关文章:

c# - 对值类型的困惑

c# - 如何让我的程序生成一个新的随机数,直到它找到一个以前没有使用过的随机数?

c# - 使用按位运算从 int 日期中提取月份 (yyyyMMdd)

c# - 如何访问继承表单上的控件?

c# - 在 WPF Slider 中,拇指没有立即用 wacom 板拖动

javascript - 选项卡上的光标 - Javascript - 立即字段

安卓。如何从我的应用程序中读取 Aztec 代码?

user-interface - 使用 Three.js 将 UI 元素直接绘制到 WebGL 区域

c# - WPF - DataGrid 仅显示基类的属性

c# - 从 WPF 页面应用程序中删除导航栏