Of course, I would question this as a best practice. However, if you really want to do this, you need not to close the window containing the UserControl .
The easiest way to do this is to set DependencyProperty to UserControl , which is just a Boolean that indicates whether the container can be closed. You would only set this to true when you want it to actually close (you probably already have a button or something that you are using now to close the control).
public Boolean AllowClose { get { return (Boolean)GetValue(AllowCloseProperty); } set { SetValue(AllowCloseProperty, value); } } public static readonly DependencyProperty AllowCloseProperty = DependencyProperty.Register("AllowClose", typeof(Boolean), typeof(MyUserControl), new UIPropertyMetadata(false));
Then, in the windows Closing event, you must set this property to true . If this is not the case, you should set e.Cancel = true ;
Using your example:
protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { if (! myUserControl.AllowClose) { MessageBox.Show("Even though most Windows allow Alt-F4 to close, I'm not letting you!"); e.Cancel = true; } else { //Content = null; // Remove child from parent - for reuse this.RemoveLogicalChild(Content); //this works faster base.OnClosing(e); { GC.Collect(); }; } }
source share