InitializeComponent() calling another method

这一生的挚爱 提交于 2021-01-20 08:37:32

问题


When I added the SelectionChanged event and of course the method in the code to handle the event to the following combobox:

....

<ComboBox Name="OrderBox" HorizontalAlignment="Left" SelectionChanged="OrderBox_OnSelectionChanged">
       <ComboBoxItem Margin="4,4,4,4" IsSelected="True">Por Nombre (A - Z)</ComboBoxItem>
       <ComboBoxItem Margin="4,4,4,4">Por Nombre (Z - A)</ComboBoxItem>
       <ComboBoxItem Margin="4,4,4,4">Por Apellido (A - Z)</ComboBoxItem>
       <ComboBoxItem Margin="4,4,4,4">Por Apellido (Z - A)</ComboBoxItem>
</ComboBox>

....

I saw debuging the application after having errors of controls not being initialized that when the application calls InitializeComponent() the first thing it does is call my combobox event handler method (OrderBox_OnSelectionChanged()). So I can't really use the event of the combobox because every controller is being loaded afterwards.

If I remove the event from the combobox xaml and the eventhandler the error won't happen, even though I have more eventhandlers, is only calling that one for some reason I can't see.

The code is as simple as this:

public MainWindow()
{
     InitializeComponent(); //FROM HERE IT GOES TO OrderBox_OnSelectionChanged()
     Displayer();
}

private void OrderBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{

}

....

Hope you know what I'm doing wrong.


回答1:


Put OrderBox.SelectionChanged+=OrderBox_OnSelectionChanged; in the MainWindow constructor and remove the SelectionChanged attribute in your xaml.




回答2:


When a form is loaded using the InitializeComponent();, the combo boxes on that pages with be set to (usually) their item at the index of -1, unless you explicitly set it otherwise. Either way, the selected item changes to its default when the form is initialized and the SelectionChanged event hits. You could work around the event being hit by putting a line of error handling:

private void OrderBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (OrderBox.SelectedItem != null)
    {
        //your code
    }
}


来源:https://stackoverflow.com/questions/51213604/initializecomponent-calling-another-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!