在 WPF 背后的代码中创建故事板 [英] Creating Storyboard in code behind in WPF

查看:38
本文介绍了在 WPF 背后的代码中创建故事板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码运行良好.

<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 中的值是 static.我需要基于系统分辨率动态传递值.所以我需要在后面的代码中创建它.可以吗?

But in this From and To values are static. I need to pass the values dynamically based system resolution. So i need it to be created in code behind. Is it possible to do ?

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

How to convert it to codebehind?

推荐答案

在使用代码时,您实际上并不需要 Storyboard,只需要基本内容的动画,就像您在问题中展示的那样.我做了一个小例子来展示它是多么容易工作.

When working in code, you don't need Storyboard really, just animations for basic things, like you show in your question. I made a little sample to show how easy it works.

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

This is the complete code behind of the mainwindow:

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 的样子:

This is how the XAML looks like:

<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 应用程序中,看看它是如何工作的,对其进行试验并尝试其他动画/属性.

Put this in a WPF app and see how it works, experiment with it and try other animations/properties.

这篇关于在 WPF 背后的代码中创建故事板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆