Mohammad Farahi
Mohammad Farahi

Reputation: 1066

C#.net - Convert animation style to code behind

I have a Style code define in ResourceDirectory to animate my popup. this is WPF code:

<Style x:Key="Hardwarepopups" TargetType="Popup">
    <Style.Triggers>
        <Trigger Property="IsOpen" Value="True">
            <Trigger.EnterActions>
                <BeginStoryboard >
                    <Storyboard>
                        <DoubleAnimation Duration="0:0:.3" Storyboard.TargetProperty="Width" From="0" To="100" AccelerationRatio=".1"/>
                    </Storyboard>
                </BeginStoryboard>
            </Trigger.EnterActions>
        </Trigger>
    </Style.Triggers>
</Style>

This is Popup:

<Popup Height="Auto" Width="Auto" Name="HardwareToolTip" StaysOpen="True" AllowsTransparency="True" Style="{StaticResource Hardwarepopups}">

It works well by handle all in XAML. I have decided to convert it to C# code like this:

void SetHarwareStyle(Popup B) {
    var RightToLeft = new DoubleAnimation()
    {
    From = 0,
    To = 100,
    Duration = TimeSpan.FromMilliseconds(300),
    AccelerationRatio = 0.1
    };
    Storyboard.SetTargetProperty(RightToLeft, new PropertyPath(WidthProperty));
    Storyboard C = new Storyboard();
    C.Children.Add(RightToLeft);

    var action = new BeginStoryboard();
    action.Storyboard = C;

    Trigger A = new Trigger { Property = Popup.IsOpenProperty, Value = true };
    A.EnterActions.Add(action);

    B.Triggers.Add(A);
}

But this line B.Triggers.Add(A); gives the error System.InvalidOperationException: 'Triggers collection members must be of type EventTrigger.' How can I solve this problem? The propose of this conversion is to change To property of DoubleAnimation in runtime.

Upvotes: 0

Views: 404

Answers (1)

Emond
Emond

Reputation: 50692

The code in the question does not reflect the XAML completely: the style is missing.

I renamed some of the variables to make it easier to read (and prevent mistakes like these)

BTW: the rightToLeftAnimation should be named leftToRightAnimation.

void SetHarwareStyle(Popup popup)
{
    var rightToLeftAnimation = new DoubleAnimation()
    {
        From = 0,
        To = 100,
        Duration = TimeSpan.FromMilliseconds(300),
        AccelerationRatio = 0.1
    };
    Storyboard.SetTargetProperty(rightToLeftAnimation, new PropertyPath(WidthProperty));
    var storyboard = new Storyboard();
    storyboard.Children.Add(rightToLeftAnimation);

    var beginStoryboard = new BeginStoryboard();
    beginStoryboard.Storyboard = storyboard;

    var trigger = new Trigger { Property = Popup.IsOpenProperty, Value = true };
    trigger.EnterActions.Add(beginStoryboard);

    var style= new Style();
    style.TargetType = typeof(Popup);
    style.Triggers.Add(trigger);

    popup.Style = style;
}

Upvotes: 1

Related Questions