1

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;
 }
jsirr13
  • 944
  • 2
  • 12
  • 38

1 Answers1

2

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

Jens Meinecke
  • 2,904
  • 17
  • 20
  • So the two options are to have my Eventhandlers check IsLoaded before executing any of its logic. Or to subscribe to the events within the Loaded event. Are there any other reasonable alternatives? – jsirr13 Jan 19 '16 at 23:24