Combobox selectionchanged event triggers without even changing the selection in the ComboBox

MangoTable picture MangoTable · Feb 16, 2011 · Viewed 12.4k times · Source

Could you help me find the error in this one: The event triggers before even the windows form is loaded. I start to see the message Box and then I click OK,after that it loads the main screen.After that everything works perfectly, I wonder what triggers the ComboBox SelectionChanged Event before even loading the window.The FillComboBoxFamilyData(SegmentCode) just creates a dataset and puts the values int he ComboBox. Please Refer to this link for complete code.

Not able to make cascading comboboxes work

Any help would be highly appreciated.Thanks.

 <ComboBox Height="23" HorizontalAlignment="Left" Margin="35,26,0,0" Name="comboBox1" VerticalAlignment="Top" Width="205" ItemsSource="{Binding Source={StaticResource tblSegmentViewSource}}"  DisplayMemberPath="Segment Name" SelectedValuePath="Segment Code" SelectionChanged="comboBox1_SelectionChanged"/>
 <ComboBox Margin="304,26,395,93" Name="comboBox2" />


    private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        MessageBox.Show(comboBox1.SelectedValue.ToString());
        SegmentCode = Convert.ToInt32(comboBox1.SelectedValue.ToString());
        FillComboBoxFamilyData(SegmentCode);

    }

Answer

HCL picture HCL · Feb 16, 2011

At the moment the data will be loaded (attached by the binding), SelectionChanged will be fired. Therefore, you have to check in your event-handler if your app is ready and all the data is loaded and attached. If not, return the event-handler without doing anything. This behaviour is by design.

ItemsSource="{Binding Source={StaticResource tblSegmentViewSource}}"  

You can use the IsLoaded-property to detect, if the binding already has been evaluated. IsLoaded will not be true unless the databinding-engine has evaluated your xaml-bindings.

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)     { 
   if(!IsLoaded){
      return;
   }
   .... your code here