Order of controls cause "System.NullReferenceException"

5

I'm doing some initial testing with WPF and this question popped up.

No error:

<DockPanel Margin="5">
    <TextBox x:Name="myTextBox" DockPanel.Dock="Right" Width="50" />
    <Slider x:Name="mySlider" Width="300" SmallChange="1" TickPlacement="BottomRight" IsSnapToTickEnabled="True" ValueChanged="mySlider_ValueChanged" Minimum="1" />
</DockPanel>

private void mySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) 
{ 
    myTextBox.Text = (Convert.ToInt32(mySlider.Value)).ToString(); 
} 

On the other hand, changing the order of the controls I get:

  

An exception of type 'System.NullReferenceException' occurred in   mySlider_error.exe but was not handled in user code

It gives error:

    <DockPanel Margin="5">
        <Slider x:Name="mySlider" Width="300" SmallChange="1" TickPlacement="BottomRight" IsSnapToTickEnabled="True" ValueChanged="mySlider_ValueChanged" Minimum="1" />
        <TextBox x:Name="myTextBox" DockPanel.Dock="Right" Width="50" />
    </DockPanel>

I know I can easily solve this scenario using, for example:

<TextBox x:Name="myTextBox" DockPanel.Dock="Right" Width="50" Text="{Binding ElementName=mySlider,Path=Value}" />

I just want to know why the exception is thrown?

    
asked by anonymous 27.02.2016 / 12:37

2 answers

1

I ended up solving this this way:

    private void atualizarValores_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (!(textBoxProduto == null))
            textBoxProduto.Text = (int.Parse(textBoxMultiplicador.Text) * int.Parse(textBoxMultiplicando.Text)).ToString();
    }
    
09.04.2016 / 12:21
0

During the construction of the Slider component in the load of the screen its value is set to the default value, in doing so, the event mySlider_ValueChanged is triggered and since the myTextBox has not yet been built it is null.

A solution would look something like this:

    private bool carregamentoCompleto = false;

    private void mySlider_ValueChanged(object sender,RoutedPropertyChangedEventArgs<double> e)
    {
        if(carregamentoCompleto)
        {
            myTextBox.Text = (Convert.ToInt32(mySlider.Value)).ToString();
        }
    }

    private void MeuWindows_Loaded(object sender, RoutedEventArgs e)
    {
        carregamentoCompleto = true;
        myTextBox.Text = (Convert.ToInt32(mySlider.Value)).ToString();
    }
    
07.04.2016 / 05:10