您的位置:首页 > 其它

SilverLight的Slider控件的学习遇到的问题

2011-05-27 11:48 246 查看
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#: using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SliderBarTest
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
//silder1.ValueChanged+=new RoutedPropertyChangedEventHandler<double>(silder1_ValueChanged);
//slider2.ValueChanged+=new RoutedPropertyChangedEventHandler<double>(slider2_ValueChanged);
}

private void silder1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
textSlider1.Text = "水平滑块的当前值为:"+silder1.Value ;
}

private void slider2_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
textSlider2.Text = "垂直滑块的当前值为:" + slider2.Value;
}

}
}


解决办法是把XAML文件中灰色部分去掉,c#文件中灰色注释部分打开。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: