In general, I ran into a NullReferenceException and, as a result of (lengthy) debugging, I found out that the ComboBox.SelectionChanged event handler calls the handler method when the application starts.
ComboBox markup:

 <ComboBox x:Name="comboBox" HorizontalAlignment="Right" Margin="5" VerticalAlignment="Top" Width="150" SelectedIndex="0" SelectionChanged="comboBox_SelectionChanged"> 

In theory, this should not be, or am I mistaken? If you need any parts of the program code, write, I will answer.

  • There is such a code var a=42; , but somewhere that does not work. If you need other parts - write, I will answer. - tym32167
  • My question is obvious: should the ComboBox.SelectionChanged event handler call methods when the application starts, if the SelectedItem of this ComboBox does not change anywhere in the code? - eXCore
  • No, the ComboBox.SelectionChanged handler should only be called when the reference to the selected item in the combo box changes. It has nothing to do with the fact that the application has started. - tym32167
  • <ComboBox x: Name = "comboBox" HorizontalAlignment = "Right" Margin = "5" VerticalAlignment = "Top" Width = "150" SelectedIndex = "0" SelectionChanged = "comboBox_SelectionChanged"> With this ComboBox description, is the handler called ? - eXCore
  • Add the code that you consider necessary, to the question - not everyone will read the comments. But it's not clear where your problem is from. Maybe because of this, SelectedIndex="0" , or maybe not. Put a breakpoint inside the handler and see the call stack. - tym32167

1 answer 1

By default, no item is selected. In this case, SelectedIndex is -1 .

If you change it to 0, then, of course, the handler will be called - you asked for it yourself!

If this is undesirable, you can do, for example, the following:

  1. You can make a boolean flag, and set it in the constructor, after InitializeComponent (this method reads and interprets XAML). The flag can be checked in the handler.
  2. You can subscribe to changes in the code-behind manually, after InitializeComponent .
  3. You can parse the previous state of the selected item in the handler by looking in SelectionChangedEventArgs .
  4. You can make the handler code more general so that it does not fall when called at the moment when no element is marked.

I would recommend to try the last option.

  • And if your studio falls from breakpoints, immediately reinstall the Studio. It is impossible to live without a well-functioning debugger. - VladD
  • It was the only time my studio fell due to breakpoint. I think if you make a minimum-requirement example, you can use it for a bug report. And yes, the second option is just what you need, thanks. And on account of falls, everything is done safely in relation to nulls. - eXCore
  • @eXCore: Please! Glad it helped! - VladD