这是“通过CompositionTarget创建对象移动动画”的代码。
代码内容如下:
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 Game
{
    public partial class CompositionTarget : UserControl
    {
        /// <summary>
        /// 填充色为蓝色,宽、高、圆角X、Y各50的矩形
        /// </summary>
        Rectangle rectangle = new Rectangle()
        {
            Fill = new SolidColorBrush(Colors.Blue),
            Width = 50,
            Height = 50,
            RadiusX = 50,
            RadiusY = 50
        };
        public CompositionTarget()
        {
            InitializeComponent();
            //将矩形添加进画布容器中
            LayoutRoot.Children.Add(rectangle);
            //注册画布容器的鼠标左键点击事件
            LayoutRoot.MouseLeftButtonDown+=new MouseButtonEventHandler(LayoutRoot_MouseLeftButtonDown);
        }
        bool isRendering = false;//是否启动了刷新
        double speed = 10;  //每次移动10像素
        double xSpeed, ySpeed; //X、Y方向的速度
        int num; //需要移动次数
        int count; //统计移动次数        private void LayoutRoot_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!isRendering)
            {
                CompositionTarget.Rendering += new EventHandler(Rendering);问题一:“CompositionTarget.Rendering”有红线提示?不是有CompositionTarget.Rendering 事件吗,怎么还提示红线说不存在?                
            isRendering = true;
            }
            Point start = new Point(Canvas.GetLeft(rectangle),Canvas.GetTop(rectangle));
            Point end = e.GetPosition(LayoutRoot);
            double distance = Math.Sqrt(Math.Pow((end.X-start.X),2)+Math.Pow((end.Y-start.Y),2));
            xSpeed = (end.X - start.X) * speed / distance;
            ySpeed = (end.Y - start.Y) * speed / distance;
            num=(int)(distance/speed);
            count = 0;
        }        private void Rendering(object sender, EventArgs e)
        {
问题二:这个事件是怎么触发执行的,没有循环语句。“CompositionTarget.Rendering 事件”会一直触发吗?

            double x = Canvas.GetLeft(rectangle);
            double y = Canvas.GetTop(rectangle);
            Canvas.SetLeft(rectangle,x+xSpeed);
            Canvas.SetTop(rectangle,y+ySpeed);
            if (count == num)
            {
                CompositionTarget.Rendering -= Rendering;
                isRendering = false;
            }
            count++;
        }
    }
}

解决方案 »

  1.   

    问题一: CompositionTarget 与你定义的类名重叠了, 请使用System.Windows.Media.CompositionTarget问题二: Rendering 会一直触发
      

  2.   

    补充 
    Rendering (相当于Flash中的Enter_Frame,在进入每帧时触发)
      

  3.   

    using System.Windows.Media;
    namespace Game这2个命名空间下都有CompositionTargetvs编译器优先认为是Game命名空间下的
      

  4.   

    CompositionTarget代表显示图面,因为画面需要不停的刷新,所有会一直触发该事件。