动画矩形:必须在非泛型静态中定义扩展方法 class

Animating rectangle: Extension method must be defined in a non-generic static class

到目前为止,这是我得到的:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    private void TestMouseDown(object sender, MouseButtonEventArgs e)
    {
        MoveTo(imageTest, 100, 100);
    }
    public static void MoveTo(this Image target, double newX, double newY)
    {
        var top = Canvas.GetTop(target);
        var left = Canvas.GetLeft(target);
        TranslateTransform trans = new TranslateTransform();
        target.RenderTransform = trans;
        DoubleAnimation anim1 = new DoubleAnimation(top, newY - top,     TimeSpan.FromSeconds(10));
        DoubleAnimation anim2 = new DoubleAnimation(left, newX - left, TimeSpan.FromSeconds(10));
        trans.BeginAnimation(TranslateTransform.XProperty, anim1);
        trans.BeginAnimation(TranslateTransform.YProperty, anim2);
    }
}

错误代码为

Extension method must be defined in a non-generic static class

前提只是使用 animation/timer 移动一个矩形,但是使用 WPF 会使这样做变得更加困难,任何帮助,甚至更好的方法,都会有所帮助!

由于您期望 this Image 作为 MoveTo 中的参数,因此正在考虑将该方法作为扩展方法。更多信息 here。试试这个:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    private void TestMouseDown(object sender, MouseButtonEventArgs e)
    {
        MoveTo(imageTest, 100, 100);
    }
    public static void MoveTo(UIElement target, double newX, double newY)
    {
        //Your code
    }
}