WPF Getting Control null reference during InitializeComponent

前端 未结 6 2096
-上瘾入骨i
-上瘾入骨i 2021-02-05 10:13

So my InitializeComponent method call in the Window\'s constructor is running through the XML and adding the controls and plugging them into their events.

6条回答
  •  北恋
    北恋 (楼主)
    2021-02-05 10:36

    I just had this issue too, and solved it by wrapping the line accessing the null control in a null check. This seems like a bit of a hack workaround.

    I think WPF is trying to be helpful here by calling our Checked event during InitializeComponent(), in an effort to ensure that any UI logic (e.g. showing/hiding related components) is executed based on the initial state of the checkbox. I tested having the Checkbox unchecked by default, and the event handler is not called, even though I have it wired to both the Checked and Unchecked events. I even reproduced this in a blank WPF project with a single Checkbox on the screen, and it behaves the same.

    The problem with this default behavior is obviously that some of the other components are not yet initialized. I think WPF should wait until all the components are initialized before firing the Checked event by default. This might not be considered a bug, but I'm gonna add a note to the relevant MSDN page anyway...

提交回复
热议问题