M
M
mayhem2012-05-26 21:53:23
WPF
mayhem, 2012-05-26 21:53:23

The ComboBox_SelectionChanged event set in XAML fires before the entire form is rendered

The form is described in XAML:

<ComboBox Name="comboPartitionTypes" SelectedIndex="0" SelectionChanged="comboPartitionTypes_SelectionChanged">
    <ComboBoxItem Content="partition1" />
    <ComboBoxItem Content="partition2" />
</ComboBox>
<StackPanel Name="panel1"></StackPanel>
<StackPanel Name="panel2"></StackPanel>


When you change the selected list item, the corresponding StackPanel should be displayed:

private void comboPartitionTypes_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
            switch (comboPartitionTypes.SelectedIndex)
            {
                case 0:
                    panel1.Visibility = System.Windows.Visibility.Visible;
                    panel2.Visibility = System.Windows.Visibility.Hidden;
                    break;

                case 1:
                    panel1.Visibility = System.Windows.Visibility.Hidden;
                    panel2.Visibility = System.Windows.Visibility.Visible;
                    break;
            }
        }


The comboPartitionTypes_SelectionChanged event, when comboPartitionTypes.SelectedIndex is specified in the XAML, is fired even before the StackPanel is initialized, as a result, panel1 and panel2 are null. If we remove comboPartitionTypes.SelectedIndex, then everything is fine, but the form is not beautiful without the selected element. You have to write at the beginning of the event handler

private void comboPartitionTypes_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (!IsLoaded) return;


Where is the logic of such behavior? Why not first draw all the elements on the form, and then start the event handling?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
gouranga, 2012-05-27
@gouranga

Josh Smith has an article on this XAML behavior.

Z
ZloyRabadaber, 2012-07-26
@ZloyRabadaber

I often find myself thinking that if you run into the need for a strict order of initialization of something, drawing, incoherent calls, etc. etc. is a sign of incorrect application architecture. It is worth sitting to think and drink tea with cookies.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question