如何设置Dialog的位置来自 .ShowDialog();
显示在mainWindows的中心.
这是我尝试设定位置的方式.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
PresentationSource source = PresentationSource.FromVisual(this);
if (source != null)
{
Left = ??
Top = ??
}
}
Run Code Online (Sandbox Code Playgroud)
che*_*web 257
在属于对话框的XAML中:
<Window ... WindowStartupLocation="CenterOwner">
Run Code Online (Sandbox Code Playgroud)
在实例化对话框时在C#中:
MyDlg dlg = new MyDlg();
dlg.Owner = this;
if (dlg.ShowDialog() == true)
{
...
Run Code Online (Sandbox Code Playgroud)
The*_*est 44
我认为使用xaml标记更容易
<Window WindowStartupLocation="CenterOwner">
Run Code Online (Sandbox Code Playgroud)
Fre*_*lad 30
您可以尝试在这样的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;
}
Run Code Online (Sandbox Code Playgroud)
小智 19
只是在代码背后.
public partial class CenteredWindow:Window
{
public CenteredWindow()
{
InitializeComponent();
WindowStartupLocation = WindowStartupLocation.CenterOwner;
Owner = Application.Current.MainWindow;
}
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*ert 16
我认为每个人对这个问题的回答都是答案应该是的部分.我会简单地把它们放在一起,我认为这是解决这个问题的最简单和优雅的方法.
首先设置您希望窗口所在的位置.这是主人.
<Window WindowStartupLocation="CenterOwner">
Run Code Online (Sandbox Code Playgroud)
在打开窗口之前,我们需要给它所有者,从另一个帖子我们可以使用当前应用程序的MainWindow的静态getter访问MainWindow.
Window window = new Window();
window.Owner = Application.Current.MainWindow;
window.Show();
Run Code Online (Sandbox Code Playgroud)
而已.
我发现这个最好
frmSample fs = new frmSample();
fs.Owner = this; // <-----
fs.WindowStartupLocation = WindowStartupLocation.CenterOwner;
var result = fs.ShowDialog();
Run Code Online (Sandbox Code Playgroud)
如果您对需要显示的窗口几乎没有控制,以下代码段可能有用
public void ShowDialog(Window window)
{
Dispatcher.BeginInvoke(
new Func<bool?>(() =>
{
window.Owner = Application.Current.MainWindow;
window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
return window.ShowDialog();
}));
}
Run Code Online (Sandbox Code Playgroud)