我的页面上有TextBlock
控件,我想在后面的代码中设置值,但我得到NullReferenceException
。 TextBlock的值根据Slider Control的当前位置而变化。要注意,发生错误时页面永远不会完全导航到NavigatedTo。我不知道我能做些什么来解决这个问题,任何想法?
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"/>
背后的代码
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;
..
}
}
答案 0 :(得分:1)
当ValueChanged
为空时,您的InitializeComponent()
会被TextBlock
触发。在InitializeComponent()
之后订阅:
在XAML中:
<TextBlock x:Name="OpacityNumberTextBlock" HorizontalAlignment="Center"/>
<Slider x:Name="MenuOpacitySlider" Minimum="1" Maximum="6" Margin="12,20,12,0" Value="1"/>
在代码背后:
public MainPage()
{
InitializeComponent();
MenuOpacitySlider.ValueChanged+=MenuOpacitySlider_ValueChanged;
}