获取和设置 WPF Canvas 控件的左侧 属性

Getting and Setting the left Property of WPF Canvas control

我知道这个问题已经被问了十几次了,但我找不到解决我问题的答案。基本上,我有一个 Canvas 控件 class 的实例,其中包含一个 Image 控件。我想在 X 轴上水平移动 Canvas 直到它消失。这是我的代码:

void moveCanvas()
{               
    int pos = Convert.ToInt32(image.GetValue(Canvas.LeftProperty)); //this line throws an exception 

    if (pos >= 800)
    {
        Canvas.SetLeft(image, 20);
    }
    else
    {
        Canvas.SetLeft(image, step); 
    }
}

void timer_Tick(object sender, EventArgs e)
{
    step += 20;
    moveCanvas(); 
}

我是 WPF 的新手,除此之外我不知道如何解决这个问题。

Canvas.Left属性的默认值为double.NaN,无法转换为int

您应该在开始动画之前初始化 Canvas.Left

Canvas.SetLeft(image, 0);
...

void moveCanvas()
{               
    var pos = Canvas.GetLeft(image); 

    if (pos >= 800)
    {
        Canvas.SetLeft(image, 20);
    }
    else
    {
        Canvas.SetLeft(image, step); 
    }
}

使用 WPF 动画移动图像可能也会简单得多:

Canvas.SetLeft(image, 0);

image.BeginAnimation(
    Canvas.LeftProperty,
    new DoubleAnimation(800, TimeSpan.FromSeconds(10));