c# - WPF - 设置相对于用户控件的对话框窗口位置

标签 c# wpf user-controls location

我需要有关设置对话框窗口相对于用户控件的位置的帮助。

我想在窗口启动时在中间用户控件中显示我的窗口。

如何找到用户控件的左侧和右侧位置?

我在我的应用程序中使用此代码,但在 WPF 中无法正常工作。

感谢您的帮助。

     private void PossitionWindow(object sender, RoutedEventArgs e)
      {
        Window wind = new Window();

        var location = this.PointToScreen(new Point(0, 0));
        wind.Left = location.X;
        wind.Top = location.Y - wind.Height;
        location.X = wind.Top + (wind.Height - this.ActualHeight) / 2;
        location.Y = wind.Left + (wind.Width - this.ActualWidth) / 2;
    }

最佳答案

这是一个小例子。

// Get absolute location on screen of upper left corner of the UserControl
Point locationFromScreen =  userControl1.PointToScreen(new Point(0, 0));

// Transform screen point to WPF device independent point
PresentationSource source = PresentationSource.FromVisual(this);
Point targetPoints = source.CompositionTarget.TransformFromDevice.Transform(locationFromScreen);

// Get Focus
Point focus = new Point();
focus.X = targetPoints.X + (userControl1.Width / 2.0);
focus.Y = targetPoints.Y + (userControl1.Height / 2.0);

// Set coordinates

Window window = new Window();
window.Width = 300;
window.Height = 300;
window.WindowStartupLocation = WindowStartupLocation.Manual;
window.Top = focus.Y - (window.Width / 2.0);
window.Left = focus.X - (window.Height / 2.0);

window.ShowDialog();

预览

preview

关于c# - WPF - 设置相对于用户控件的对话框窗口位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44119226/

相关文章:

c# - ProgressBar 中值为 0 时如何显示 PART_Indicator? WPF

c# - XAML 2 组合框颜色样式与资源字典?

WPF 如何让 UserControl 继承 Button?

wpf - WPF Window 无法识别同一项目中定义的用户控件时该怎么办?

c# - 比较c#中的日期并考虑空值

c# - 如何在 MDI 父窗体下一次打开一个窗体?

c# - 为什么必须在 foreach C# 中显式声明 ListItem

c# - 如何在 phantomjs 中禁用外部 javascript 执行/站点请求

wpf - Locbaml 是如何工作的?

c# - 将 XAML 形状绘制到 DrawingContext?