WPF: why my Combobox SelectionChanged event is fir

2019-09-06 03:59发布

问题:

So i have application and another sub form:

public partial class SubForm: MetroWindow...

And here is how i am open my Sub form from my main form:

SubForm subForm = new SubForm();
subForm.ShowDialog();

Inside my Sub form i have this chart control:

<telerik:RadCartesianChart
    x:Name="chart" />

And Combobox:

<ComboBox
    Name="cbInterfaces" 
    ItemsSource="{Binding Path=(my:MyClass.MachineInterfaces)}"
    SelectedIndex="0"
    SelectionChanged="cbInterfaces_SelectionChanged"/>

So i notice that after the Sub form oped right after InitializeComponent method, the code is go into my Combobox SelectionChanged event and my chart control is still null and not created yet. So i cannot use it until use again my Combobox and change selection again (in this case my chart not null)

回答1:

You could just return from the event handler immediately if the window or the RadCartesianChart haven't yet been initialized or loaded:

private void cbInterfaces_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (!this.IsLoaded || chart == null || !chart.IsLoaded)
        return; //do nothing

    //your code...
}

Yes but the problem is that after this form created and opened i want to see my snuff immediately in my chat instead of change my combobox selection again ...

Set the SelectedIndex property programmatically after the call to the InitializeComponent() method then:

public partial class SubForm : Window
{
    public SubForm()
    {
        InitializeComponent();
        cbInterfaces.SelectedIndex = 0;
    }

    private void cbInterfaces_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        //...
    }
}

<ComboBox
    Name="cbInterfaces" 
    ItemsSource="{Binding Path=(local:MyClass.MachineInterfaces)}"
    SelectionChanged="cbInterfaces_SelectionChanged"/>