Sha*_*aku 0 c# wpf runtime-error event-handling nullreferenceexception
调用“sliderValue.Content = widthValue”(如下在滑块的 ValueChanged 事件处理程序中定义)时出现奇怪的空对象引用错误。
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>
Run Code Online (Sandbox Code Playgroud)
代码:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
错误(因调用 sliderValue.Content = widthValue 引发):
Object reference not set to an instance of an object.
System.NullReferenceException was unhandled by user code (...)
Run Code Online (Sandbox Code Playgroud)
但是,如果我将该语句移至另一个事件处理程序中,一切都会正常工作。当我从 ValueChanged 事件调用它时,它只会引发此错误,这很奇怪。
从您发布的内容来看,它似乎sliderValue
是无效的。我不确定这到底是如何发生的,因为您在构造函数中使用了它...无论如何,这个示例非常适合您使用 WPF 绑定:
<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" Minimum="1" />
<Label Content="{Binding ElementName=WidthSlider, Path=Value}" HorizontalAlignment="Left" Margin="262,50,0,0" VerticalAlignment="Top"/>
Run Code Online (Sandbox Code Playgroud)
编辑:
好的,我发现你的问题是什么:当InitializeComponent()
被调用时,值发生widthSlider
变化。这会触发你的widthSlider_ValueChanged
事件,但是因为widthSlider
之前已经初始化过sliderValue
,sliderValue
所以会null
在此时。
所以基本上,只需添加:
if(sliderValue != null)
{
...
}
Run Code Online (Sandbox Code Playgroud)
参加您的活动,一切都会好起来的。
我之前在 WPF 和类似事件中注意到了这一点。他们会真正告诉你什么时候会发生什么变化。
PS:您确实应该提到,在此类情况下,异常发生在应用程序启动之前。它可以节省一些时间。
归档时间: |
|
查看次数: |
1570 次 |
最近记录: |