2

在我的 XAML 中,我在网格中有一个列表框和一些文本框,在画布中有一个反应角:

Title="MainWindow" Height="350" Width="500" WindowStartupLocation="CenterScreen">
<Grid>
<ListBox HorizontalAlignment="Left"
         Margin="12,12,0,12"
         Name="listBoxContainer"
         Width="120">
    <ListBoxItem Content="Item1" />
    <ListBoxItem Content="Item2" />
    <ListBoxItem Content="Item3" />
</ListBox>

<TextBox Height="23"
         Margin="138,12,85,0"
         Name="textBoxAddress"
         VerticalAlignment="Top" />

<TextBox Margin="138,41,85,12"
         Name="textBoxMsg" />

<Button Content="Button"
        Name="buttonAnimation"
        Width="75"
        Margin="0,10,5,0"
        Height="23"
        VerticalAlignment="Top"
        HorizontalAlignment="Right"
        Click="Button1Click" />

<Canvas Name="CanvasAnimation">
    <Rectangle Canvas.Left="408" 
               Canvas.Top="140" 
               Height="50" 
               Name="rectAnimation" 
               Stroke="Black" 
               Width="50" />
</Canvas>
</Grid>

从我后面的代码中,我可以将矩形从它的位置移动到一段距离:

private void Button1Click(object sender, RoutedEventArgs e)
{
    var trs = new TranslateTransform();
    var anim3 = new DoubleAnimation(0, -200, TimeSpan.FromSeconds(2));
    trs.BeginAnimation(TranslateTransform.XProperty, anim3);
    trs.BeginAnimation(TranslateTransform.YProperty, anim3);
    CanvasAnimation.RenderTransform = trs;
}

我想知道如何通过坐标将矩形从其位置移动到另一个位置?就像让矩形移动到列表框或文本框的位置一样

4

2 回答 2

3

请注意,以下代码假定画布上的按钮坐标和表单上的坐标相同。这不是最佳的,您应该找到更好的解决方案,例如将按钮放在画布上。

private void Button1Click(object sender, RoutedEventArgs e)
{
  //Point relativePoint = buttonAnimation.TransformToAncestor(this).Transform(new Point(0, 0));
  Point relativePoint = buttonAnimation.TransformToVisual(CanvasAnimation).Transform(new Point(0, 0));

  var moveAnimX = new DoubleAnimation(Canvas.GetLeft(rectAnimation), relativePoint.X, new Duration(TimeSpan.FromSeconds(10)));
  var moveAnimY = new DoubleAnimation(Canvas.GetTop(rectAnimation), relativePoint.Y, new Duration(TimeSpan.FromSeconds(10)));

  rectAnimation.BeginAnimation(Canvas.LeftProperty, moveAnimX);
  rectAnimation.BeginAnimation(Canvas.TopProperty, moveAnimY);
}
于 2013-02-20T12:41:53.863 回答
0

很抱歉回答迟了,但听起来你想设置一个依赖属性。

rectAnimation.SetValue(Canvas.TopProperty, 0.0);
rectAnimation.SetValue(Canvas.LeftProperty, 0.0);

这将(立即)将矩形放置在包含画布的顶部和左侧。

于 2014-10-01T03:32:21.843 回答