c# - wpf Storyboard死亡

标签 c# wpf xaml timer storyboard

C#:

public partial class MainWindow : Window
{
    Storyboard a = new Storyboard();
    int i;
    public MainWindow()
    {
        InitializeComponent();
        a.Completed += new EventHandler(a_Completed);
        a.Duration = TimeSpan.FromMilliseconds(10);
        a.Begin();
    }

    void a_Completed(object sender, EventArgs e)
    {
        textblock.Text = (++i).ToString();
        a.Begin();
    }
}

XAML:

<Window x:Class="Gui.MainWindow" x:Name="control"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="300">
<Canvas>
    <TextBlock Name="textblock"></TextBlock>
</Canvas>

这段代码有什么问题? Storyboard在 20-50 轮后停止。每次不同的数字

最佳答案

我相信这是因为在您的代码中, Storyboard的动画时钟和 TextBlock 的文本依赖属性之间没有建立任何关系。如果非要我猜的话,我会说 Storyboard 何时结束,这是由于 DependencyProperty(TextBlock.Text 是一个 DependencyProperty)更新管道的污染而在某种程度上是随机的。创建如下所示的关联(RunTimeline 或 RunStoryboard 都可以,但显示查看此内容的替代方法):

public partial class Window1 : Window
{
    Storyboard a = new Storyboard();
    StringAnimationUsingKeyFrames timeline = new StringAnimationUsingKeyFrames();
    DiscreteStringKeyFrame keyframe = new DiscreteStringKeyFrame();

    int i;

    public Window1()
    {
        InitializeComponent();

        //RunTimeline();
        RunStoryboard();
    }

    private void RunTimeline()
    {
        timeline.SetValue(Storyboard.TargetPropertyProperty, new PropertyPath("(TextBlock.Text)"));
        timeline.Completed += timeline_Completed;
        timeline.Duration = new Duration(TimeSpan.FromMilliseconds(10));
        textblock.BeginAnimation(TextBlock.TextProperty, timeline);
    }

    private void RunStoryboard()
    {
        timeline.SetValue(Storyboard.TargetPropertyProperty, new PropertyPath("(TextBlock.Text)"));
        a.Children.Add(timeline);
        a.Completed += a_Completed;
        a.Duration = new Duration(TimeSpan.FromMilliseconds(10));
        a.Begin(textblock);
    }

    void timeline_Completed(object sender, EventArgs e)
    {
        textblock.Text = (++i).ToString();
        textblock.BeginAnimation(TextBlock.TextProperty, timeline);
    }

    void a_Completed(object sender, EventArgs e)
    {
        textblock.Text = (++i).ToString();
        a.Begin(textblock);
    }
}

只要我让它运行,它就对我有效(比以往任何时候都长 10 倍)。

蒂姆

关于c# - wpf Storyboard死亡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/315427/

相关文章:

c# - 在 C# 中附加到鼠标的工具提示

c# - session 关闭后无法访问引用的对象

c# - 如何获取存储在资源中的图像的 Uri

c# - xamarin.forms 从 xaml 绑定(bind)到属性

c# - 在 C# 中序列化、压缩和加密

c# - C# 的 CRC 4 实现

wpf - 还原对象是用户在 WPF 中单击 "Cancel"

c# - 防止数据网格中的行更改

c# - 带有 C# WPF 的 EMGU

wpf - 在 'System.Windows.StaticResourceExtension' 上提供值引发异常