在滑块的 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 事件中调用它时,它只会引发此错误,这很奇怪。