在WPF中的代码中创建Storyboard

Raj*_*Raj 25 .net c# wpf animation eventtrigger

以下代码工作正常.

<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>
Run Code Online (Sandbox Code Playgroud)

但在这方面From,To价值观是静态的.我需要根据系统分辨率动态传递值.所以我需要在后面的代码中创建它.有可能吗?

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

Ter*_*rry 42

在代码中工作时,您不需要真正的Storyboard,只需要基本功能的动画,就像您在问题中显示的那样.我做了一个小样本来展示它是多么容易.

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

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是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>
Run Code Online (Sandbox Code Playgroud)

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

  • 这个问题是针对故事板的,所以这不是答案 (2认同)