How to animate TextBlock when its value changes in

2019-05-11 02:58发布

问题:

I have the following Storyboard

<Storyboard x:Name="DeleteStoryboard">
    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="StatusTextBlock">
        <EasingDoubleKeyFrame KeyTime="0" Value="1"/>
        <EasingDoubleKeyFrame KeyTime="0:0:4" Value="1"/>
        <EasingDoubleKeyFrame KeyTime="0:0:5" Value="0"/>
    </DoubleAnimationUsingKeyFrames>
</Storyboard>

and the following TextBlock

<TextBlock x:Name="StatusTextBlock" Text="{Binding Status}">

Both are in SettingsFlyout not a Page.

I want the Storyboard to start when the TextBlock value changes.

I'm using MVVM, so please no code-behind stuff unless absolutely necessary.

I tries searching for hints and tried different combination of Behaviors, Triggers and VisualState but reached nowhere.

回答1:

Again, not sure if we are 100% agreeing. But, still, here's how you can do it:

public class MyViewModel : INotifyPropertyChanged
{
    public string Text { get; set; }
    public event PropertyChangedEventHandler PropertyChanged;
}

public void Loaded()
{
    var myBox = new TextBox();
    var myAni = new Storyboard();
    var MyVvm = new MyViewModel();

    // sensible approach
    myBox.TextChanged += (s, e) => myAni.Begin();

    // forced approach
    MyVvm.PropertyChanged += (s, e) =>
    {
        if (e.PropertyName.Equals("Text"))
            myAni.Begin();
    };
}

In the end, you are the developer of your own app. not me.

If you are willing to use behaviors, you can also do the same thing this way:

<Page.Resources>
    <Storyboard x:Name="FadeAway">
        <DoubleAnimation Duration="0:0:1" To="0" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="textBox" d:IsOptimized="True"/>
    </Storyboard>
</Page.Resources>

<TextBox x:Name="textBox">
    <Interactivity:Interaction.Behaviors>
        <Core:EventTriggerBehavior EventName="TextChanged">
            <Media:ControlStoryboardAction Storyboard="{StaticResource FadeAway}"/>
        </Core:EventTriggerBehavior>
    </Interactivity:Interaction.Behaviors>
</TextBox>

I suppose you can have your "pure" MVVM approach using a behavior. It gets you 100% XAML, and that makes some developers feel warm and fuzzy; I get that. And, I like behaviors. Look. I don't want to argue with you here, it's just that the top approach is certainly not "wrong".

Learn more about behaviors: http://blog.jerrynixon.com/2013/10/everything-i-know-about-behaviors-in.html

Best of luck.