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 08:46

You must set a parent window to your window (Owner) and then set the WindowStartupLocation property to "CenterParent"

查看更多
做自己的国王
3楼-- · 2020-02-02 08:50

I found this one the best

frmSample fs = new frmSample();
fs.Owner = this; // <-----
fs.WindowStartupLocation = WindowStartupLocation.CenterOwner;
var result = fs.ShowDialog();
查看更多
forever°为你锁心
4楼-- · 2020-02-02 08:50

XAML:

    <Window WindowStartupLocation="CenterScreen">
查看更多
狗以群分
5楼-- · 2020-02-02 08:53

I think it's easier to use xaml markup

<Window WindowStartupLocation="CenterOwner">
查看更多
We Are One
6楼-- · 2020-02-02 08:55

Just in code behind.

public partial class CenteredWindow:Window
{
    public CenteredWindow()
    {
        InitializeComponent();

        WindowStartupLocation = WindowStartupLocation.CenterOwner;
        Owner = Application.Current.MainWindow;
    }
}
查看更多
够拽才男人
7楼-- · 2020-02-02 08:56

For the child window, set at the XAML

WindowStartupLocation="CenterOwner"

To call your child window as a dialog and center of the parent, call it from the parent window, e.g

private void ConfigButton_OnClick(object sender, RoutedEventArgs e)
{
    var window = new ConfigurationWindow
    {
        Owner = this
    };
    window.ShowDialog();
}
查看更多
登录 后发表回答