WPF Getting Control null reference during InitializeComponent

前端 未结 6 2106
-上瘾入骨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:44

    You should be able to check the IsInitialized or IsLoaded properties on your Window to verify it has finished initializing/loading. Otherwise, you would need to check for null or add your event subscriptions in your code behind (after InitializeComponent).

    Also, you may be able to adjust how you access the elements. For example, if you have something like:

    
    

    Then in your code behind you can get the list box several ways:

    private void OnListBoxSelectionChanged(object sender, SelectionChangedEventArgs e) {
        ListBox lb = this.listBox; // May be null
        ListBox lb = sender as ListBox; // Should never be null
        ListBox lb = e.Source as ListBox; // Same as sender in this case
        ListBox lb = e.OriginalSource as ListBox; // Always the element that started the event (if handler is not attached directly to ListBox).
        // ... Do Something ...
    }
    

提交回复
热议问题