Mohamad Kahfie
Mohamad Kahfie

Reputation: 67

How to write dynamic DoubleAnimationUsingKeyFrames with c# and xaml

I have written static animation with DoubleAnimationUsingKeyFrames :

<Storyboard x:Name="MyCount" Completed="MyCount_Completed">
            <DoubleAnimationUsingKeyFrames EnableDependentAnimation="True" Storyboard.TargetName="MyProgressBar" Storyboard.TargetProperty="(RangeBase.Value)">
                <DiscreteDoubleKeyFrame KeyTime="0:0:0" Value="100"/>
                <DiscreteDoubleKeyFrame KeyTime="0:0:1" Value="90"/>
                <DiscreteDoubleKeyFrame KeyTime="0:0:2" Value="80"/>
                <DiscreteDoubleKeyFrame KeyTime="0:0:3" Value="70"/>
                <DiscreteDoubleKeyFrame KeyTime="0:0:4" Value="60"/>
                <DiscreteDoubleKeyFrame KeyTime="0:0:5" Value="50"/>
                <DiscreteDoubleKeyFrame KeyTime="0:0:6" Value="40"/>
                <DiscreteDoubleKeyFrame KeyTime="0:0:7" Value="30"/>
                <DiscreteDoubleKeyFrame KeyTime="0:0:8" Value="20"/>
                <DiscreteDoubleKeyFrame KeyTime="0:0:9" Value="10"/>
                <DiscreteDoubleKeyFrame KeyTime="0:0:10" Value="0"/>
            </DoubleAnimationUsingKeyFrames>
        </Storyboard>

Now I like to make this code (value and time parts) dynamic with c#. How can I do that ?

Upvotes: 0

Views: 201

Answers (1)

Sean O&#39;Neil
Sean O&#39;Neil

Reputation: 1241

    <Storyboard x:Name="MyCount" Completed="MyCount_Completed">
        <DoubleAnimationUsingKeyFrames EnableDependentAnimation="True" Storyboard.TargetName="MyProgressBar" Storyboard.TargetProperty="(RangeBase.Value)">
        <DiscreteDoubleKeyFrame KeyTime="{Binding MyStoryboardTimeKeyframeA}" Value="{Binding MyStoryboardValueKeyframeA}"/>
    </DoubleAnimationUsingKeyFrames>

In your view model or whatever your Data Context class is:

public class MyViewModel : INotifyPropertyChanged
{
    private double _myStoryboardValueKeyframeA;
    public double MyStoryboardValueKeyframeA
    {
        get
        {
            return _myStoryboardValueKeyframeA;
        }
        set
        {
            _myStoryboardValueKeyframeA = value;
            OnPropertyChanged("MyStoryboardValueKeyframeA");
        }
    }

    private TimeSpan _myStoryboardTimeKeyframeA;
    public TimeSpan MyStoryboardTimeKeyframeA
    {
        get
        {
            return _myStoryboardTimeKeyframeA;
        }
        set
        {
            _myStoryboardTimeKeyframeA = value;
            OnPropertyChanged("MyStoryboardTimeKeyframeA");
        }
    }

    protected void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, e);
    }

    public void OnPropertyChanged(string propertyName)
    {
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Upvotes: 2

Related Questions