如何淡出文本,更改文本并将其淡入?

时间:2011-06-02 23:56:06

标签: wpf animation fade textblock

我在datatemplate中为数据网格中的单元格使用TextBlock。我有一个要求说明当单元格的值发生变化时,文本应该是:

  • 在更改前淡出
  • 值应该改变
  • 再次淡出

目前我使用TargetUpdated RoutedEvent来触发动画以使文本逐渐消失然后再返回。但是,在文本已经在屏幕上更改了值之后,就会发生淡入淡出。

<DataTemplate>
    <Border>
        <TextBlock Name="templateTextBlock" Text="{Binding Path=FirstName, NotifyOnTargetUpdated=True}" />
    </Border>
    <DataTemplate.Triggers>
        <EventTrigger RoutedEvent="Binding.TargetUpdated">
            <BeginStoryboard>
                <Storyboard AutoReverse="True">
                    <DoubleAnimation Storyboard.TargetName="templateTextBlock" Storyboard.TargetProperty="Opacity" To=".1" Duration="0:0:.5" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </DataTemplate.Triggers>
</DataTemplate>

我的问题是如何实现所需效果 - 淡出,更改文字,淡入?

非常感谢。

1 个答案:

答案 0 :(得分:10)

写了一个应该这样做的交互行为:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
<TextBlock Text="{Binding Name, NotifyOnTargetUpdated=True}">
    <i:Interaction.Behaviors>
        <b:AnimatedTextChangeBehavior AnimationDuration="0:0:0.1" />
    </i:Interaction.Behaviors>
</TextBlock>
class AnimatedTextChangeBehavior : Behavior<TextBlock>
{
    public Duration AnimationDuration { get; set; }

    private string OldValue = null;
    private string NewValue = null;

    DoubleAnimation AnimationOut;
    DoubleAnimation AnimationIn;

    protected override void OnAttached()
    {
        base.OnAttached();

        AnimationOut = new DoubleAnimation(1, 0, AnimationDuration, FillBehavior.HoldEnd);
        AnimationIn = new DoubleAnimation(0, 1, AnimationDuration, FillBehavior.HoldEnd);
        AnimationOut.Completed += (sOut, eOut) =>
        {
            AssociatedObject.SetCurrentValue(TextBlock.TextProperty, NewValue);
            OldValue = NewValue;
            AssociatedObject.BeginAnimation(TextBlock.OpacityProperty, AnimationIn);
        };

        Binding.AddTargetUpdatedHandler(AssociatedObject, new EventHandler<DataTransferEventArgs>(Updated));
    }

    private void Updated(object sender, DataTransferEventArgs e)
    {
        string value = AssociatedObject.GetValue(TextBlock.TextProperty) as string;
        AssociatedObject.BeginAnimation(TextBlock.OpacityProperty, AnimationOut);
        NewValue =  value;
        if (OldValue == null)
        {
            OldValue = value;
        }
        AssociatedObject.SetCurrentValue(TextBlock.TextProperty, OldValue);
    }
}

如果您不想使用Blend SDK的交互性,您可以将代码重构为单独的类并使用TextBlock的Loaded事件进行设置。< / p>