C# InitializeComponent()调用另一个方法

C# InitializeComponent()调用另一个方法,c#,wpf,xaml,events,components,C#,Wpf,Xaml,Events,Components,当我将SelectionChanged事件以及代码中处理事件的方法添加到以下组合框时: .... <ComboBox Name="OrderBox" HorizontalAlignment="Left" SelectionChanged="OrderBox_OnSelectionChanged"> <ComboBoxItem Margin="4,4,4,4" IsSelected="True">Por Nombre (A - Z)</ComboBox

当我将SelectionChanged事件以及代码中处理事件的方法添加到以下组合框时:

....

<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>

....

希望你知道我做错了什么。

Put
OrderBox.SelectionChanged+=OrderBox\u OnSelectionChangedInitializeComponent()加载表单时,请在
主窗口中的
构造函数中删除
SelectionChanged
属性
,除非您明确设置为其他方式,否则该页面上的组合框(通常)必须设置为其索引为-1的项。无论哪种方式,当表单初始化且
SelectionChanged
事件点击时,所选项目将更改为其默认值。您可以通过放置一行错误处理来解决被击中的事件:

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

初始化时,组合框复选框将从未设置更改为初始值。这是因为它们不能被取消设置。无法避免调用event-handler.Tested,调用也会进入if条件,因此无法以这种方式工作@抱歉,我没有看到您在XAMLI中设置了一个选定项,我自己也忘了,组合框的属性没有selected和SelectedIndex=“-1”,它可以正常工作。@safteinz太棒了!如果您没有将组合框项目作为选定项发送,则不需要将选定的索引明确声明为-1,尽管这样做总是比较安全。现在可以工作了,非常感谢您,先生。为什么xaml组合框中的事件会使构造函数在加载其他事件之前加载该精确的事件方法?它会运行该事件,因为xaml代码指定启动时选择的项目,所以它会更改SelectedItem,然后调用该事件。此外,您通常不会在Stackoverflow上写“先生”。
private void OrderBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (OrderBox.SelectedItem != null)
    {
        //your code
    }
}