P.a.
P.a.

Reputation: 21

WPF - Set dialog window position relative to user control

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;
    }

Upvotes: 2

Views: 2694

Answers (1)

Dominic Jonas
Dominic Jonas

Reputation: 5005

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

Upvotes: 3

Related Questions