WPF : How to set a Dialog position to show at the

2020-02-02 08:41发布

How to set Dialog's position that came from .ShowDialog(); to show at the center of the mainWindows.

This is the way I try to set position.

private void Window_Loaded(object sender, RoutedEventArgs e)
{        
    PresentationSource source = PresentationSource.FromVisual(this);
    if (source != null)
    {
        Left = ??
        Top = ??
    }
}

标签: wpf dialog
14条回答
放荡不羁爱自由
2楼-- · 2020-02-02 09:08

To get a WPF Dialog to position at the centre of a Windows Forms parent form I passed the parent form to the dialog since Application.Current didn't return the Windows Form parent (I assume it only works if the parent app is WPF).

public partial class DialogView : Window
{
    private readonly System.Windows.Forms.Form _parent;

    public DialogView(System.Windows.Forms.Form parent)
    {
        InitializeComponent();

        _parent = parent;
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this.Left = _parent.Left + (_parent.Width - this.ActualWidth) / 2;
        this.Top = _parent.Top + (_parent.Height - this.ActualHeight) / 2;
    }
}

set the WindowStartupLocation on the WPF Dialog:

<Window WindowStartupLocation="CenterParent">

and the way the Windows Form loads the WPF dialog is like this:

DialogView dlg = new DialogView();
dlg.Owner = this;

if (dlg.ShowDialog() == true)
{
    ...
查看更多
你好瞎i
3楼-- · 2020-02-02 09:10

I think everyone's answers to this question are parts to what the answer should be. I will simply put them together which I believe is the easiest and elegant approach to this problem.

First setup where you want the window to be located. Here it's the owner.

<Window WindowStartupLocation="CenterOwner">

Before opening the window we need to give it the owner and from another post we can access the MainWindow using the static getter for the current application's MainWindow.

        Window window = new Window();
        window.Owner = Application.Current.MainWindow;
        window.Show();

That's it.

查看更多
登录 后发表回答