简体   繁体   English

为什么此WPF滑块会引发异常?

[英]Why does this WPF slider throw an exception?

Code: 码:

private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            updateTickCounter(slider1.Value);
        }

        private void updateTickCounter(double value)
        {
            tickCounter.Content = value.ToString();
        }

XAML: XAML:

<Slider Height="32" HorizontalAlignment="Right" Margin="0,21,61,0" Name="slider1" VerticalAlignment="Top" Width="200" IsSnapToTickEnabled="True" Orientation="Horizontal" TickFrequency="1" TickPlacement="BottomRight" Value="1" Minimum="1" Maximum="10" ValueChanged="slider1_ValueChanged" />

I'm trying to have a slider that starts at value 1 out of 10. Every time the slider is moved I want a label called 'tickCounter' to change text. 我试图使用一个从10开始的值1开始的滑块。每次移动该滑块时,我都希望一个名为“ tickCounter”的标签来更改文本。

The code above throws an exception when ran -- "Object reference not set to an instance of an object." 上面的代码在运行时引发异常-“对象引用未设置为对象的实例。”

However, once I change both the values of "Value" and "Minimum" in XAML it works fine. 但是,一旦我在XAML中同时更改了“值”和“最小”的值,它就可以正常工作。 It's as if I can't make it not start at zero. 好像我不能让它不从零开始。 It's really weird. 真的很奇怪 Any help? 有什么帮助吗?

如果我查看提供的堆栈跟踪,那么我唯一可能的nullexception似乎是tickCounter == null

Rather than using events to update the label, use DataBinding . 与其使用事件来更新标签,不如使用DataBinding

<Slider Name="slider1" IsSnapToTickEnabled="True" Orientation="Horizontal" Value="1" Minimum="1" Maximum="10" />

<Label Name="tickCounter" Content="{Binding Path=Value, ElementName=slider1"} />

Also, if you do not need any of the additional abilities of a Label you should use a TextBlock . 另外,如果不需要Label任何其他功能,则应使用TextBlock

<TextBlock Name="tickCounter" Text="{Binding Path=Value, ElementName=slider1"} />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM