Reputation: 5147
I've noticed that if a user control (or maybe any Framework element) gets added and removed immediately from the visual tree, the Loaded event is never raised but the Unloaded event always raises.
To reproduce the issue, create a blank UWP project, add the following XAML and code behind to the MainPage:
<Page ...>
<Grid>
<StackPanel>
<Button Click="Button_Click" Content="Click Me"/>
<Border x:Name="border"/>
</StackPanel>
</Grid>
</Page>
Code Behind:
public MainPage() {
this.InitializeComponent();
this.control = new UserControl();
this.control.Loaded += OnLoaded;
this.control.Unloaded += OnUnloaded;
}
private void Button_Click(object sender, RoutedEventArgs e) {
this.border.Child = this.control;
this.border.Child = null;
}
private void OnLoaded(object sender, RoutedEventArgs e) {
System.Diagnostics.Debug.WriteLine("Loaded.");
}
private void OnUnloaded(object sender, RoutedEventArgs e) {
System.Diagnostics.Debug.WriteLine("Unloaded");
}
Clicking on the button multiple times gives the following output:
Unloaded Unloaded Unloaded Unloaded Unloaded Unloaded Unloaded
FrameworkEvent.Loaded (MSDN):
Occurs when a FrameworkElement has been constructed and added to the object tree, and is ready for interaction
FrameworkEvent.Unloaded (MSDN):
Occurs when this object is no longer connected to the main object tree.
What exactly is happening here? If the control is not added to visual tree because it is removed immediately, why the Unloaded method is being called? Is there any documentation for this behavior?
Upvotes: 1
Views: 775
Reputation: 1241
This isn't really a programming question, but rather a critique on the semantics used by the developers at Microsoft. I'll answer it with an analogy. I would have commented this instead but it's too long.
Loading luggage on a plane is slow. I have to do one bag at a time. Unloading is instant, I pull a lever and they all fall out.
As soon as I begin loading the first piece of luggage on a plane, I shout out 'Loading!' (the 'Loading' event).
When I finish loading all the luggage I shout out 'Loaded'. (the 'Loaded' event).
If I get a call telling me the flight is cancelled I pull the lever and remove whatever luggage I already put on there and I shout 'Unloaded' (the 'Unloaded' event). Regardless if I had actually finished loading all the luggage in the first place or not is irrelevant. I've unloaded it after I already started loading.
So semantically, you see how you can unload something that hasn't been loaded yet. Think of the 'Loaded' event to mean 'Fully Loaded' and think of the 'Loading' event to mean 'Partially Loaded.' Whatever real-life problem this behavior was causing you, look to the 'Loading' event instead of the 'Loaded' event.
Upvotes: 1