2008-11-24 146 views
4

C#:WPF故事板死亡

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> 

什麼是錯的代碼? 故事板在20-50回合後停止。每次有不同的號碼

+0

非常有趣的問題,我發現這停止了,當我的鼠標移過TextBlock我有時得到1500。 – 2008-11-24 21:18:36

回答

2

我相信這是因爲在您的代碼中Storyboard的動畫時鐘與TextBlock的Text DependencyProperty之間沒有關係。如果我不得不猜測,我會說故事板是什麼時候搞出來的,由於弄髒了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長於倍它曾經花光了)否則。

Tim