Random animation in Silverlight
I have a Silverlight image.
<Image Source="pics/pic1.png" Stretch="Fill" Canvas.Left="50" Canvas.Top="50" Width="100" Height="100" MouseLeftButtonUp="startRandomAnim">
<Image.Resources>
<Storyboard x:Name="randomMove">
<!-- code -->
</Storyboard>
</Image.Resources>
</Image>开发者_运维百科
I'd like it to move to a random point on a canvas when clicked. How do I do that? Can I do it in the XAML file or do I have to handle it in the underlying C#?
To get a random value you need to use some code.
You could, in order to use the least amount of C# possible, create a class that contains the coordinates of the target for the animation, create an object of this class and put it in the DataContext of the image and bind the storyboard to the coordinates. Then, when the use clicks, generate the random coordinates and start the animation.
You cannot generate random numbers in a storyboard. I would create the animation in XAML:
<Image Source="pics/pic1.png" Stretch="Fill" Canvas.Left="50" Canvas.Top="50" Width="100" Height="100" MouseLeftButtonUp="startRandomAnim"
x:Name="myImage">
<Image.Resources>
<Storyboard x:Key="anim">
<DoubleAnimation Storyboard.TargetName="myImage" Storyboard.TargetProperty="(Canvas.Left)" To="30" Duration="0:0:0.1" />
</Storyboard>
</Image.Resources>
</Image>
Then in your image click handler set a random location and start the animation:
var sb= image.Resources["anim"] as Storyboard;
var anim = sb.Children[0] as DoubleAnimation;
anim.To = // some random position
sb.Begin();
精彩评论