在WPF中创建故事板在code背后故事、WPF、code

2023-09-03 06:21:56 作者:女人犯贱是宿命‰

下面code是工作的罚款。

The following code is working fine.

<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>

但在这个值的静态的。我需要传递的价值观动态的系统解决方案。所以,我需要它在code后面的创建。是否有可能呢?

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 ?

如何将其转换为codebehind?

How to convert it to codebehind?

推荐答案

在code工作时,你不需要故事板真的,只是动画基本的东西,就像你在你的问题显现。 我做了一个小样本来说明如何轻松它的工作原理。

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.

这是主窗口背后的完整code:

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.