【发布时间】:2013-11-07 02:22:22
【问题描述】:
在滑块的 ValueChanged 事件处理程序内部调用“sliderValue.Content = widthValue”时出现奇怪的空对象引用错误。
XAML:
<Window x:Class="StrangeError.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="166.066" Width="326.351">
<Grid>
<Slider x:Name="widthSlider" HorizontalAlignment="Left" Margin="6,56,0,0" VerticalAlignment="Top" Width="257" TickFrequency="10" SmallChange="0.01" TickPlacement="BottomRight" IsSnapToTickEnabled="True" Ticks="1, 2, 3, 4, 5, 6, 7, 8, 9, 10" ValueChanged="widthSlider_ValueChanged" Minimum="1"/>
<Label x:Name="sliderValue" Content="" HorizontalAlignment="Left" Margin="262,50,0,0" VerticalAlignment="Top"/>
</Grid>
代码:
namespace StrangeError
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
int widthValue;
public MainWindow()
{
InitializeComponent();
widthValue = 1;
sliderValue.Content = 1;
}
private void widthSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
widthValue = (int)widthSlider.Value;
sliderValue.Content = widthValue;
}
}
}
错误(由调用 sliderValue.Content = widthValue 引发):
Object reference not set to an instance of an object.
System.NullReferenceException was unhandled by user code (...)
但是,如果我将该语句移到另一个事件处理程序中,则一切正常。当我从 ValueChanged 事件中调用它时,它只会引发此错误,这很奇怪。
【问题讨论】:
-
有没有附上看看什么是null?
-
sliderValue和widthSlider都是非空的吗? -
是的。我用初始化位更新了原始问题。
-
真的是“奇怪的空对象引用错误”。
-
您应该发布更多代码,因为我感觉您正在做一些其他奇怪的事情。也许您在加载 UI 之前调用了
sliderValue.Content。
标签: c# wpf event-handling runtime-error nullreferenceexception