WPF : How to set a Dialog position to show at the center of the application?

前端 未结 14 2593
天命终不由人
天命终不由人 2020-12-02 16:18

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.

         


        
14条回答
  •  臣服心动
    2020-12-02 17:07

    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:

    
    

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

    DialogView dlg = new DialogView();
    dlg.Owner = this;
    
    if (dlg.ShowDialog() == true)
    {
        ...
    

提交回复
热议问题