开发者

Error when trying to cast from System.Double to System.Single

I am sure this will turn out to be something simple. I have the following Silverlight 4 C# code:

Rectangle r = new Rectangle();
r.Stroke = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
r.SetValue(Canvas.LeftProperty, 150f);
r.SetValue(Canvas.TopProperty, 50f);
r.Width = 100;
r.Height = 100;

LayoutRoot.Children.Add(r);

For some reason, when I run my application, it is getting an error on the SetValue lines. The error I am getting is:

Uncaught Error: Unhandled Error in Silverlight Application DependencyProperty of type System.D开发者_高级运维ouble cannot be set on an object of type System.Single.

I tried to cast implicitly to Single, but still got the same error. Any ideas?


You're passing in a boxed float, and the rectangle is then trying to unbox it to a double. Just pass in doubles to start with, and it should be fine:

r.SetValue(Canvas.LeftProperty, 150d);
r.SetValue(Canvas.TopProperty, 50d);

Note that Canvas.Left and Canvas.Top are of type double, not float.


These properties have type double. You are passing single precision values, floats. Pass doubles and all will be well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜