动画后,GetLeft()在窗口外的面板上返回0

时间:2013-10-21 12:52:34

标签: c# wpf animation canvas

我还在学习wpf,所以我在这里有点困惑。 代码在按钮的碰撞上为窗口左侧的StackPanel设置动画,然后在原始位置点击另一个按钮。 它可以工作但是如果你在show或hide上单击两次,它会移动面板然后执行动画,即使它没有必要(代码比我更清晰)。 我试图拦截面板的实际位置以在必要时停止动画,但属性GetLeft()总是返回0.

xaml

        <Canvas>
            <StackPanel x:Name="pannello_laterale" Width="100" Panel.ZIndex="10" Canvas.Left="0" Canvas.Top="0" Canvas.Bottom="0" Background="Azure">
                <Button>
                    <StackPanel>
                        <Label>bim</Label>
                        <Label>bum</Label>
                    </StackPanel>
                </Button>
                <Button>bam</Button>
            </StackPanel>

            <Button x:Name="Mostra" Content="Show" Canvas.Left="201" Canvas.Top="56" Width="75" Click="Mostra_Click"/>
            <Button x:Name="Nascondi" Content="Hide" Canvas.Left="201" Canvas.Top="107" Width="75" Click="Nascondi_Click"/>
        </Canvas>

代码

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
        using System.Windows;
        using System.Windows.Controls;
        using System.Windows.Data;
        using System.Windows.Documents;
        using System.Windows.Input;
        using System.Windows.Media;
        using System.Windows.Media.Imaging;
        using System.Windows.Navigation;
        using System.Windows.Shapes;

        using System.Windows.Media.Animation;

    namespace Prova_WPF2
    {
        /// <summary>
        /// Logica di interazione per MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }

            private void Mostra_Click(object sender, RoutedEventArgs e)
            {
                posizione.MoveXTo(pannello_laterale, -100.00, 0.00, 0.3);
            }

            private void Nascondi_Click(object sender, RoutedEventArgs e)
            {
                posizione.MoveXTo(pannello_laterale, 0.00, -100.00, 0.3);
            }

        }

        public static class posizione
        {

            public static void MoveXTo(this StackPanel target, double FromX, double ToX, double Time)
            {
                var left = Canvas.GetLeft(target);
                //MessageBox.Show(left.ToString());
                TranslateTransform transformation = new TranslateTransform();
                target.RenderTransform = transformation;
                DoubleAnimation animation = new DoubleAnimation(FromX, ToX, TimeSpan.FromSeconds(Time));
                transformation.BeginAnimation(TranslateTransform.XProperty, animation);
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

您没有使用动画更改目标元素的Left属性,而是应该监控TranslateTransform.X