Silverlight Slider 控件“未将对象引用设置到对象的实例”错误解决方案

当在xaml文件中设置Value值之后,编译解决方案后,会报错“未将对象引用设置到对象的实例”

sColour.xaml文件代码

代码
<UserControl x:Class="sample.sColour"
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="120"/>
<RowDefinition Height="120"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Rectangle Grid.Row="0" Grid.Column="1" x:Name="PreviewColour" Fill="#FFFF6600" Margin="15" ></Rectangle>
<StackPanel Grid.Row="1" Grid.Column="1">
<TextBlock FontSize="12">Color</TextBlock>
<TextBox x:Name="HexColour" Text="#FFFF6600" Height="30" Width="160" Margin="5" HorizontalAlignment="Left" FontSize="11"></TextBox>
</StackPanel>
<StackPanel Grid.Row="0" Grid.Column="0" Grid.RowSpan="2" VerticalAlignment="Center">
<TextBlock Text="Alpha" FontSize="11" Margin="10,15,0,0"/>
<Slider x:Name="SliderAlpha" Margin="20,0,10,0" Maximum="255" Value="255" ValueChanged="Slider_ValueChanged"/>
<TextBlock Text="Red" FontSize="11" Margin="10,15,0,0"/>
<Slider x:Name="SliderRed" Margin="20,0,10,0" Maximum="255" Value="255" ValueChanged="Slider_ValueChanged"/>
<TextBlock Text="Green" FontSize="11" Margin="10,15,0,0"/>
<Slider x:Name="SliderGreen" Margin="20,0,10,0" Maximum="255" Value="102" ValueChanged="Slider_ValueChanged"/>
<TextBlock Text="Blue" FontSize="11" Margin="10,15,0,0"/>
<Slider x:Name="SliderBlue" Margin="20,0,10,0" Maximum="255" Value="0" ValueChanged="Slider_ValueChanged"/>
</StackPanel>
</Grid>
</UserControl>

 

 

sColour.xaml.cs文件代码

 

代码
1 using System.Windows.Documents;
2  using System.Windows.Input;
3  using System.Windows.Media;
4  using System.Windows.Media.Animation;
5  using System.Windows.Shapes;
6 namespace sample
7 {
8 public partial class sColour : UserControl
9 {
10 public sColour()
11 {
12 InitializeComponent();
13 }
14 private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
15 {
16 Color myColor = Color.FromArgb((byte)SliderAlpha.Value, (byte)SliderRed.Value, (byte)SliderGreen.Value, (byte)SliderBlue.Value);
17        PreviewColour.Fill = new SolidColorBrush(myColor);
18 HexColour.Text = myColor.ToString();
19 }
20 }
21 }

 

仔细查看代码,貌似没有什么错误,但是总是会提示“未将对象引用设置到对象的实例”。后来经过查看资料,这可能是silverlight的一个bug,如果定义了ValueChanged,似乎不能给Slider的value属性在Xaml中赋初值。我们可以在sColour的构造函数中赋值:

 

 

1public sColour()
2{
3     InitializeComponent();
4this.SliderAlpha.Value = 255;
5this.SliderRed.Value = 255;
6this.SliderGreen.Value = 102;
7this.SliderBlue.Value = 0;
8}

 

运行界面,一个简易的取色器

 

posted @ 2010-12-30 16:44  junyuz  阅读(3272)  评论(2编辑  收藏  举报