Nice programing

WPF : 응용 프로그램의 중앙에 표시 할 대화 상자 위치를 설정하는 방법은 무엇입니까?

nicepro 2020. 10. 17. 12:20
반응형

WPF : 응용 프로그램의 중앙에 표시 할 대화 상자 위치를 설정하는 방법은 무엇입니까?


.ShowDialog();메인 윈도우의 중앙에 표시하기 위해 나온 Dialog의 위치를 ​​설정하는 방법 .

이것이 제가 위치를 설정하는 방법입니다.

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

다음과 같이 Loaded 이벤트에서 MainWindow를 확보하려고 할 수 있습니다.

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    Application curApp = Application.Current;
    Window mainWindow = curApp.MainWindow;
    this.Left = mainWindow.Left + (mainWindow.Width - this.ActualWidth) / 2;
    this.Top = mainWindow.Top + (mainWindow.Height - this.ActualHeight) / 2;
}

대화 상자에 속하는 XAML에서 :

<Window ... WindowStartupLocation="CenterOwner">

그리고 C #에서 대화 상자를 인스턴스화 할 때 :

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

if (dlg.ShowDialog() == true)
{
    ...

xaml 마크 업을 사용하는 것이 더 쉽다고 생각합니다.

<Window WindowStartupLocation="CenterOwner">

코드 뒤에서.

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

        WindowStartupLocation = WindowStartupLocation.CenterOwner;
        Owner = Application.Current.MainWindow;
    }
}

이 질문에 대한 모든 사람의 대답은 대답이 무엇인지에 대한 부분이라고 생각합니다. 이 문제에 대한 가장 쉽고 우아한 접근 방식이라고 생각하는 그것들을 간단히 정리할 것입니다.

창을 배치하려는 첫 번째 설정. 여기 주인입니다.

<Window WindowStartupLocation="CenterOwner">

창을 열기 전에 소유자를 제공해야하며 다른 게시물에서 현재 응용 프로그램의 MainWindow에 대한 정적 getter를 사용하여 MainWindow에 액세스 할 수 있습니다.

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

그게 다야.


나는 이것이 최고임을 발견했다

frmSample fs = new frmSample();
fs.Owner = this; // <-----
fs.WindowStartupLocation = WindowStartupLocation.CenterOwner;
var result = fs.ShowDialog();

WPF 대화 상자를 Windows Forms 부모 양식의 중앙에 배치하려면 Application.Current가 Windows Form 부모를 반환하지 않았기 때문에 부모 양식을 대화 상자에 전달했습니다 (부모 앱이 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;
    }
}

WPF 대화 상자에서 WindowStartupLocation을 설정합니다.

<Window WindowStartupLocation="CenterParent">

Windows Form이 WPF 대화 상자를로드하는 방법은 다음과 같습니다.

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

if (dlg.ShowDialog() == true)
{
    ...

부모 창을 창 (소유자)으로 설정 한 다음 WindowStartupLocation 속성을 "CenterParent"로 설정해야합니다.


MainWindow의 크기가 조정되거나 최대화되면 mainWindow.Width 및 mainWindow.Height가 XAML에 설정된 값을 반영하기 때문에 Fredrik Hedblad 응답에 추가하고 싶습니다.

실제 값을 원하면 mainWindow.ActualWidth 및 mainWindow.ActualHeight를 사용할 수 있습니다.

private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        Application curApp = Application.Current;
        Window mainWindow = curApp.MainWindow;
        this.Left = mainWindow.Left + (mainWindow.ActualWidth - this.ActualWidth) / 2;
        this.Top = mainWindow.Top + (mainWindow.ActualHeight - this.ActualHeight) / 2;
    }

XAML :

    <Window WindowStartupLocation="CenterScreen">

이 코드는 xaml에서 WindowStartupLocation 속성을 사용하지 않으려는 경우에 작동합니다.

private void CenterWindowOnApplication()
{
    System.Windows.Application curApp = System.Windows.Application.Current;
    Window mainWindow = curApp.MainWindow;
    if (mainWindow.WindowState == WindowState.Maximized)
    {
        // Get the mainWindow's screen:
        var screen = System.Windows.Forms.Screen.FromRectangle(new System.Drawing.Rectangle((int)mainWindow.Left, (int)mainWindow.Top, (int)mainWindow.Width, (int)mainWindow.Height));
        double screenWidth = screen.WorkingArea.Width;
        double screenHeight = screen.WorkingArea.Height;
        double popupwindowWidth = this.Width;
        double popupwindowHeight = this.Height;
        this.Left = (screenWidth / 2) - (popupwindowWidth / 2);
        this.Top = (screenHeight / 2) - (popupwindowHeight / 2);
    }
    else
    {
        this.Left = mainWindow.Left + ((mainWindow.ActualWidth - this.ActualWidth) / 2;
        this.Top = mainWindow.Top + ((mainWindow.ActualHeight - this.ActualHeight) / 2);
    }
}

작업 표시 줄이 mainWindow를 더 작게 만들기 때문에 "screen.WorkingArea"를 사용하고 있습니다. 창을 화면 중앙에 배치하려면 대신 "screen.Bounds"를 사용할 수 있습니다.


자식 창의 경우 XAML에서 설정합니다.

WindowStartupLocation="CenterOwner"

자식 창을 대화 상자 및 부모의 중심으로 호출하려면 부모 창에서 호출하십시오.

private void ConfigButton_OnClick(object sender, RoutedEventArgs e)
{
    var window = new ConfigurationWindow
    {
        Owner = this
    };
    window.ShowDialog();
}

표시해야하는 창을 거의 제어 할 수없는 경우 다음 스 니펫이 유용 할 수 있습니다.

    public void ShowDialog(Window window)
    {
        Dispatcher.BeginInvoke(
            new Func<bool?>(() =>
            {
                window.Owner = Application.Current.MainWindow;
                window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                return window.ShowDialog();
            }));
    }

For the sake of documentation, I'll add here an example of how I achieved something similar. What I needed was a popup that covered the entire parent Window content area (excluding the title bar), but simply centering the dialog and stretching its content didn't work because the dialog was always offset a little bit from the bottom.

Note about user experience: It's not nice not being able to drag/close the parent window when the borderless dialog is showing, so I would reconsider using it. I also decided not to do this after posting this answer, but will leave it up for others to look at.

After some googling and testing, I finally managed to do it like this:

var dialog = new DialogWindow
{
    //this = MainWindow
    Owner = this
};

dialog.WindowStartupLocation = WindowStartupLocation.Manual;
dialog.WindowStyle = WindowStyle.None;
dialog.ShowInTaskbar = false;
dialog.ResizeMode = ResizeMode.NoResize;
dialog.AllowsTransparency = true;

var ownerContent = (FrameworkElement) Content;
dialog.MaxWidth = ownerContent.ActualWidth;
dialog.Width = ownerContent.ActualWidth;
dialog.MaxHeight = ownerContent.ActualHeight;
dialog.Height = ownerContent.ActualHeight;    

var contentPoints = ownerContent.PointToScreen(new Point(0, 0));
dialog.Left = contentPoints.X;
dialog.Top = contentPoints.Y;

dialog.ShowDialog();

The DialogWindow is a Window and its owner is set to the main application Window. The WindowStartupLocation must be set to Manual for manual positioning to work.

Result:

No dialog showing

Modal dialog showing

I don't know if there's an easier way to do this, but nothing else seemed to work for me.

참고URL : https://stackoverflow.com/questions/4306593/wpf-how-to-set-a-dialog-position-to-show-at-the-center-of-the-application

반응형