26

以下代码工作正常。

<Window.Triggers>
    <EventTrigger RoutedEvent="Window.Loaded">
        <BeginStoryboard>
            <Storyboard>
                <DoubleAnimation Duration="0:0:.8" Storyboard.TargetProperty="Left" From="1920" To="0" AccelerationRatio=".1"/>
            </Storyboard>
        </BeginStoryboard>
    </EventTrigger>
</Window.Triggers>

但是在这个FromTo值是静态的。我需要动态传递基于系统分辨率的值。所以我需要在后面的代码中创建它。有可能吗?

如何将其转换为代码隐藏?

4

3 回答 3

49

在代码中工作时,您真的不需要故事板,只需要基本事物的动画,就像您在问题中显示的那样。我做了一个小样本来展示它的工作原理。

这是主窗口背后的完整代码:

namespace WpfCSharpSandbox
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            WidenObject(150, TimeSpan.FromSeconds(1));
        }

        private void WidenObject(int newWidth, TimeSpan duration)
        {
            DoubleAnimation animation = new DoubleAnimation(newWidth, duration);
            rctMovingObject.BeginAnimation(Rectangle.WidthProperty, animation);
        }
    }
}

这是 XAML 的样子:

<Window x:Class="WpfCSharpSandbox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Sandbox" Height="350" Width="525">
    <Grid Background="#333333">
        <Rectangle x:Name="rctMovingObject" Fill="LimeGreen" Width="50" Height="50"/>
    </Grid>
</Window>

把它放在一个 WPF 应用程序中,看看它是如何工作的,试验它并尝试其他动画/属性。

于 2013-04-09T11:56:35.103 回答
1

添加 djerry 的注释示例代码如下所示:

var anim = new DoubleAnimation {
                                From = 1920, 
                                To = 1, 
                               };

wnd.BeginAnimation(Window.LeftProperty, anim); 

并且您必须在窗口加载的事件处理程序中拥有此代码。希望这可以帮助。

于 2013-04-09T11:47:26.763 回答
0

问题的示例代码是关于动画Window.Left属性的,我正在寻找确切的情况,但给定的答案仅适用于一次性用例。
具体来说:如果动画已经执行,然后通过拖放手动移动窗口,则相同的动画过程将无法按需要再次运行。动画将始终使用最近动画运行的结束坐标。
所以如果你移动了窗口,它会在开始新动画之前跳回来:

https://imgur.com/a/hxRCqm7

要解决该问题,需要AnimationClock在动画完成后从动画属性中删除任何内容。

这是通过使用ApplyAnimationClockor BeginAnimationwithnull作为第二个参数来完成的:

public partial class MainWindow : Window
{
    // [...]

    private void ButtonMove_Click(object sender, RoutedEventArgs e)
    {
        AnimateWindowLeft(500, TimeSpan.FromSeconds(1));
    }

    private void AnimateWindowLeft(double newLeft, TimeSpan duration)
    {
        DoubleAnimation animation = new DoubleAnimation(newLeft, duration);
        myWindow.Completed += AnimateLeft_Completed;
        myWindow.BeginAnimation(Window.LeftProperty, animation);
    }

    private void AnimateLeft_Completed(object sender, EventArgs e)
    {
        myWindow.BeginAnimation(Window.LeftProperty, null);
        // or
        // myWindow.ApplyAnimationClock(Window.LeftProperty, null);
    }
}

XAML:

<Window x:Class="WpfAppAnimatedWindowMove.MainWindow"
        // [...]
        Name="myWindow">

结果:
https ://imgur.com/a/OZEsP6t

另请参阅Microsoft Docs - HandoffBehavior Enum 的备注部分

于 2019-11-26T16:28:43.943 回答