Search code examples
c#wpfeventscanvasloaded

Is canvas load event occurring after other events expected?


It's not clear to me what the order of events are when subscribing to events in xaml. I'm not sure why, but my canvas1_SizeChangedevent occurs first, and causes a null reference exception because image has not yet been initialized because the Loaded event has not happened yet. I'll probably end up just moving the canvas1_SizeChanged event subscription to the Loaded handler, however, I'm still curious why the timing is the way it is. Below is a code snippet display my issue.

In xaml:

<Canvas Name="canvas1" Loaded="canvas1_Loaded" SizeChanged="canvas1_SizeChanged">

in xaml.cs:

 private Image image;
 private void canvas1_Loaded(object sender, RoutedEventArgs e)
 {
     image = new Image();
 }

 private void canvas1_SizeChanged(object sender, SizeChangedEventArgs e)
 {
      content = image.Content;
 }

Solution

  • The normal paradigm is this:

    1. Call control constructor.
    2. Set up control properties (Location, Size, EventHandlers etc)
    3. Add Control to parent (if not parent control itself)
    4. Show parent

    It is at step 2. that you would be getting the call to canvas1_SizeChanged event handler.

    It is only after step 4. that eh canvas_Loaded event handler is called