To be sure, I would really question this as a Best Practice. However, if you really want to do this, then you need to prevent the window containing the UserControl from closing.
The easiest way to do this is to set a DependencyProperty on your UserControl that is simply a Boolean that flags 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 would check for that property to be set to true. If it is not, then you would 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(); };
}
}