Assume that I have two WPF windows: window_One and window_Two.
- window_One has one button. Clicking this button opens window_Two.
- window_Two contains a User Control.
- This user control has one button that closes window_Two.
How can I achieve this scenario?
Inside the custom control that you've created. You can access the parent window from within the button event click.
Either by using the visual tree:
or by simply:
Of course, the other option would be to create a custom event that says "MyButtonClicked" and then have the window that hosts the UserControl to listen to this event and when the Event is fired, you close the current window.
Cheers!
You can try EventAggregator to implement this event driven logic across different ViewModel.
http://www.codeproject.com/Articles/355473/Prism-EventAggregator-Sample
We implemented this to close Window1 from Window2 getting opened, but it should work in any scenario to close any window from anywhere if you place these code parts in their appropriate areas:
Create a class that stores a
Window
object, and a function that will close it:CloseWindow.cs
In the parent window (window you want to close - Window2, in this case?), in its onload event, set its
Window
object equal toCloseWindow.WinObject
:Then, in the child's onload event (or, in the case of the OP, in Window2's User Control's button event), have it perform the
CloseParent()
function: