WPF: why my Combobox SelectionChanged event is fired before my chart control created

China☆狼群 提交于 2019-12-12 02:29:26

问题


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


来源:https://stackoverflow.com/questions/42833185/wpf-why-my-combobox-selectionchanged-event-is-fired-before-my-chart-control-cre

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