Search code examples
c#windows-phone-7windows-phone-8slidertextblock

Setting TextBlock Text in Code Behind Gives NullReferenceException


I have a TextBlock control on my page in which I would like to set the value in the code behind, but I am getting a NullReferenceException. The value of the TextBlock changes according to the current position of a Slider Control. To note, the page never gets fully NavigatedTo when the error occurs. I'm not sure what I can do to solve this, any ideas?

XAML

<TextBlock x:Name="OpacityNumberTextBlock" HorizontalAlignment="Center">
<Slider x:Name="MenuOpacitySlider"  Minimum="1" Maximum="6" Margin="12,20,12,0" 
                    ValueChanged="MenuOpacitySlider_ValueChanged" Value="1"/>

Code Behind

public void MenuOpacitySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
    {
        Slider slider = sender as Slider;

        //Round the value so it is a whole number even when the slider is dragged
        slider.Value = Math.Round(slider.Value);

        num = (int)slider.Value;

        switch (num)
        {
            case 1:
                OpacityNumberTextBlock.Text = "1"; //NullReferenceException
                break;
            ..
        }
    }

Solution

  • Your ValueChanged is fired in InitializeComponent() while the TextBlock is null. Subscribe after InitializeComponent():

    In XAML:

    <TextBlock x:Name="OpacityNumberTextBlock" HorizontalAlignment="Center"/>
    <Slider x:Name="MenuOpacitySlider"  Minimum="1" Maximum="6" Margin="12,20,12,0" Value="1"/>
    

    In code behind:

    public MainPage()
    {
        InitializeComponent();
        MenuOpacitySlider.ValueChanged+=MenuOpacitySlider_ValueChanged;
    }