2013-02-20 36 views
0

在我的XAML我有一個畫布列表框,並在網格中的一些文本框和一個reactangle:從代碼移到一個矩形在畫布上,在WPF背後

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; 
} 

我想知道如何通過座標將矩形從其位置移動到另一個位置?像具有矩形移動到列表框或文本框

回答

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); 
} 
+0

是的,你是對的。想你的解決方案,但不是最優的xD – 2013-02-20 13:03:56

+0

增加了一個線,以改善畫布=形式的依賴。 – nvoigt 2013-02-20 17:30:16

+0

這實際上起作用,所以直到我對如何解決這個問題有了另一個想法之後,我將使用您的解決方案。謝謝! – 2013-02-25 08:21:16

0

對不起,對於遲來的答案,但它聽起來像你想設置一個依賴屬性。

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

這將(立即)將矩形放置在包含畫布的頂部和左側。

相關問題