【问题标题】:Animating ellipsis in XAMLXAML 中的省略号动画
【发布时间】:2015-06-20 15:54:13
【问题描述】:

想象一些文字:

<TextBlock>Loading...</TextBlock>

我想要一个省略号(... 字符)的简单动画,它在...... 之间以缓慢的周期振荡,以便给人一种正在发生某事的印象。

在 XAML for WPF 中是否有一种简单的方法可以做到这一点?

【问题讨论】:

  • 并谎称 UI 确实知道加载过程?让我们看看我能不能想到点什么。

标签: .net wpf xaml animation ellipsis


【解决方案1】:

纯 XAML 解决方案可能如下所示:

<TextBlock>
    <TextBlock.Triggers>
        <EventTrigger RoutedEvent="Loaded">
            <BeginStoryboard>
                <Storyboard Duration="0:0:3" RepeatBehavior="Forever">
                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Text">
                        <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="Loading."/>
                        <DiscreteObjectKeyFrame KeyTime="0:0:1" Value="Loading.."/>
                        <DiscreteObjectKeyFrame KeyTime="0:0:2" Value="Loading..."/>
                    </ObjectAnimationUsingKeyFrames>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </TextBlock.Triggers>
</TextBlock>

【讨论】:

  • 这正是我所追求的,而且效果很好。非常感谢。
【解决方案2】:

如果你需要一些东西,你可以用沙盒来玩。

class LoadingElipsis : INotifyPropertyChanged
{
    public LoadingElipsis()
    {
        Thread thread = new Thread(this.Spin);
        thread.Start();
    }

    public string Display
    {
        get
        {
            switch(DateTime.Now.Second % 3)
            {
                default: return "Loading.";
                case 1: return "Loading..";
                case 2: return "Loading...";
            }
        }
    }

    protected void Spin()
    {
        while (true)
        {
            Thread.Sleep(1000);
            Notify("Display");
        }
    }

    protected void Notify(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

还有 XAML

<Window.Resources>
    <project:LoadingElipsis x:Key="loading" />
</Window.Resources>    
<Grid DataContext="{StaticResource ResourceKey=loading}">
    <TextBlock Text="{Binding Display}" Background="Red"/>
</Grid>

免责声明: 不是一个完整的示例,具有可以取消的正式后台线程,但通过一些努力,您可以让它从您正在加载的内容中报告信息等。

对于那些简单的 XAML 动画还不够的场景。

【讨论】:

  • 我强烈建议使用计时器(最好是 DispatcherTimer)而不是带睡眠的线程。
  • 我同意,这只是为了让它起步。在关键帧动画上使用这种方法的唯一原因是您必须在代码中设置它或具有更动态的效果。使用它(无需睡眠),您可以发布有意义的更新,例如完成百分比等。
猜你喜欢
  • 2012-10-12
  • 1970-01-01
  • 2012-10-11
  • 1970-01-01
  • 1970-01-01
  • 2019-06-28
  • 1970-01-01
  • 2020-12-26
  • 1970-01-01
相关资源
最近更新 更多