您的位置:首页 > 其它

Silverlight4学习笔记--方块鼠标跟随

2010-03-26 17:02 274 查看
XAML代码:
=============================================

<UserControl x:Class="Test_SL.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="lr" Background="Blue">
<StackPanel HorizontalAlignment="Left"></StackPanel>
<Rectangle Height="50" HorizontalAlignment="Left" Name="rectangle1" Stroke="{x:Null}" StrokeThickness="1" VerticalAlignment="Top" Width="50" Fill="Red" Margin="10,10,0,0" RadiusX="5" RadiusY="5">
<Rectangle.RenderTransform>
<TranslateTransform x:Name="tt" X="0" Y="0" />
</Rectangle.RenderTransform>
</Rectangle>
</Grid>
</UserControl>

CS代码:

=============================================

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 Test_SL
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.MyInit();
}

private void MyInit()
{
this.lr.MouseLeftButtonDown += new MouseButtonEventHandler(lr_MouseLeftButtonDown);
}

void lr_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Storyboard sb = new Storyboard();
//获取当前鼠标位置。
Point p = e.GetPosition(this.lr);

//横向运动的动画。
DoubleAnimation daX = new DoubleAnimation()
{
To = p.X,
Duration = TimeSpan.FromMilliseconds(500)
};
Storyboard.SetTargetProperty(daX, new PropertyPath("X"));
Storyboard.SetTarget(daX, this.tt);
sb.Children.Add(daX);

//纵向运动的动画。
DoubleAnimation daY = new DoubleAnimation()
{
To = p.Y,
Duration = TimeSpan.FromMilliseconds(100)
};
Storyboard.SetTargetProperty(daY, new PropertyPath("Y"));
Storyboard.SetTarget(daY, this.tt);
sb.Children.Add(daY);

//开始动画。
sb.Begin();
}
}
}

完成了,貌似挺简单。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: