我还在学习wpf,所以我在这里有点困惑。该代码在按钮的叮当声上在窗口左侧为 StackPanel 设置动画,然后在原始位置单击另一个按钮。它可以工作,但是如果您在显示或隐藏时单击两次,它会移动面板然后执行动画,即使它不是必需的(代码比我更清楚)。我试图截取面板的实际位置以在必要时停止动画,但属性 GetLeft() 始终返回 0。
xml
<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);
}
}
}