WPF Create sibling window and close current one
What I need is such an event handler in my window class.
void someEventHandler(object sender, RoutedEventArgs e)
{
MyNewWindow mnw = new MyNewWindow();
mnw.Owner = Window.GetWindow(this);
mnw.ShowDialog();
this.Close();
}
Window.GetWindow(this) returns the parent window of the current window.
I had thought when the owner of the new window is the parent window of the current one, it would wait for the parent; and not the current one. But it did not work that way. 开发者_StackOverflow社区Current window waits for the execution of the new and closes only after.
If I use Show() instead of ShowDialog() for some reason the window is not shown at all.
Probably I need some delegate methods but I am not sure where to start.
Edit: I guess I need to improve the question for future references: The new window should be a dialog to the parent window. If I use Show() the parent window becomes accesible and I dont want that. If I use ShowDialog() it becomes a dialog to the current window, meaning that the current window does not close until the new window is closed, and I dont want that either.
Closing a window causes any windows that it owns to be closed.
If you just want the owner window to not be visible, try this;
void someEventHandler(object sender, RoutedEventArgs e)
{
MyNewWindow mnw = new MyNewWindow();
mnw.Owner = this;
this.Hide(); // not required if using the child events below
mnw.ShowDialog();
}
You'll likely want to hook up some event in the parent window that acts accordingly when you close the child window depending on your requirements.
EDIT
You could perhaps control the hiding of the (multiple parents) from the child;
void OnLoad(object sender, RoutedEventArgs e)
{
this.Owner.Hide();
}
void Closed(object sender, RoutedEventArgs e)
{
this.Owner.Show();
}
If I understand what you're trying to do you want to close the current window and replace it with a MyNewWindow that is a child of the window that was the original window's parent (probably the app's main window).
To do that you should be using:
mnw.Owner = this.Owner;
instead of calling GetWindow, which gives you back the current Window instance. The purpose of GetWindow is to obtain the Window which contains some other UIElement, like a Button farther down the tree. When passing in a Window instance, you just get back what you passed in.
Calling ShowDialog()
blocks. That means, the method returns only when mnw
is closed and only then is the original window closed.
If you change that to Show()
, mnw
is closed as soon as you call Close()
on the original window. because Window.GetWindow(this)
returns this
. Thus, you set the owner to this
and when you close this
, mnw
gets closed too. That leaves us with:
MyNewWindow mnw = new MyNewWindow();
mnw.Owner = this.Owner; // may not be necessary
mnw.Show();
this.Close();
This code seems to work for me.
精彩评论