GetLeft() 在动画将面板移动到窗口旁边后返回 0
本文关键字:窗口 返回 移动 动画 GetLeft | 更新日期: 2023-09-27 18:36:19
我还在学习wpf,所以我在这里有点困惑。该代码在窗口左侧的按钮叮当声上对 StackPanel 进行动画处理,然后在原始位置单击另一个按钮。它可以工作,但是如果您在显示或隐藏时单击两次,它会移动面板,然后执行动画,即使没有必要(代码比我更清晰)。如有必要,我试图拦截面板的实际位置以停止动画,但属性 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);
}
}
}
您不会使用动画更改目标元素的 Left
属性,而是应该监视TranslateTransform.X
。