2

I need help with Setting dialog window position relative to User control.

I want to show my window in the middle user control when a window starts.

How can I find the left and tom location of my User Control?

I use this code in my app but does not work correctly in WPF.

Thank you for help.

     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;
    }
2
  • Do you want to show the dialog in the center of your application main window?
    – user2819245
    May 22, 2017 at 17:59
  • No, I want show dialog window in the center of my User Control.
    – P.a.
    May 22, 2017 at 18:14

1 Answer 1

3

Here is a small example.

// 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

preview

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.