在我的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;
}
我想知道如何通过坐标将矩形从其位置移动到另一个位置?就像让矩形移动到列表框或文本框的位置
答案 0 :(得分:2)
请注意,下面的代码假定画布上和表单上按钮的坐标是相同的。这不是最佳选择,您应该找到更好的解决方案,例如将按钮放在画布上。
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);
}
答案 1 :(得分:0)
对于迟到的回答感到抱歉,但听起来您想要设置依赖项属性。
rectAnimation.SetValue(Canvas.TopProperty, 0.0);
rectAnimation.SetValue(Canvas.LeftProperty, 0.0);
这将(立即)将矩形放置在包含画布的顶部和左侧。