[英]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
. 我的页面上有一个
TextBlock
控件,我想在其中的代码中设置该值,但是却收到了NullReferenceException
。 The value of the TextBlock changes according to the current position of a Slider Control. TextBlock的值根据滑块控件的当前位置而变化。 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 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;
..
}
}
Your ValueChanged
is fired in InitializeComponent()
while the TextBlock
is null. 当
TextBlock
为null时,在InitializeComponent()
触发ValueChanged
。 Subscribe after InitializeComponent()
: 在
InitializeComponent()
之后订阅:
In XAML: 在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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.