SilverLight的Slider控件的学习遇到的问题
时间:2011-05-27 来源:紫电雷龙
Slider控件有两个设定最大(Maximum)最小(Minimum)范围的属性,默认分别为1,0.当人为设定这两个值并在ValueChanged事件中引用了该控件就会报NoneReferenceException的错误,原因是Slider控件没有被实例化,因为我们人为的设置了最大最小属性,在过初始化方法(InitializeComponent)时触发了ValueChanged事件,这个时候Slider还没有加载完就引用了它的实例,报了错。
报错代码如下:
XAML:
<UserControl x:Class="SliderBarTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="30"/>
<RowDefinition Height="20"/>
<RowDefinition Height="180"/>
<RowDefinition Height="20"/>
</Grid.RowDefinitions>
<TextBlock Text="选择控件-Silder" FontSize="24" FontWeight="Bold" FontFamily="Comic Sans MS" Grid.Row="0"/>
<Slider x:Name="silder1" Minimum="0" Maximum="10" Grid.Row="1" Margin="10,0,10,0" ValueChanged="silder1_ValueChanged"/>
<TextBlock FontSize="15" FontFamily="Comic Sans MS" Text="silder1" Grid.Row="2" Margin="10,0,10,0" x:Name="textSlider1"/>
<Slider x:Name="slider2" Minimum="1" Maximum="10" Orientation="Vertical" Grid.Row="3" Margin="10,10,370,10" ValueChanged="slider2_ValueChanged" />
<TextBlock Text="slider2" FontSize="15" FontFamily="Comic Sans MS" Grid.Row="4" Margin="10,0,10,0" x:Name="textSlider2"/>
</Grid>
</UserControl>
C#: 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Net;
5 using System.Windows;
6 using System.Windows.Controls;
7 using System.Windows.Documents;
8 using System.Windows.Input;
9 using System.Windows.Media;
10 using System.Windows.Media.Animation;
11 using System.Windows.Shapes;
12
13 namespace SliderBarTest
14 {
15 public partial class MainPage : UserControl
16 {
17 public MainPage()
18 {
19 InitializeComponent();
20 //silder1.ValueChanged+=new RoutedPropertyChangedEventHandler<double>(silder1_ValueChanged);
21 //slider2.ValueChanged+=new RoutedPropertyChangedEventHandler<double>(slider2_ValueChanged);
22 }
23
24 private void silder1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
25 {
26 textSlider1.Text = "水平滑块的当前值为:"+silder1.Value ;
27 }
28
29 private void slider2_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
30 {
31 textSlider2.Text = "垂直滑块的当前值为:" + slider2.Value;
32 }
33
34
35 }
36 }
解决办法是把XAML文件中灰色部分去掉,c#文件中灰色注释部分打开。
相关阅读 更多 +