代码之家  ›  专栏  ›  技术社区  ›  Mohammad Farahi

C.NET-将动画样式转换为代码隐藏

  •  0
  • Mohammad Farahi  · 技术社区  · 6 年前

    我在resourcedirectory中有一个样式代码定义来设置弹出窗口的动画。这是wpf代码:

    <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>
    

    这是弹出窗口:

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

    它可以很好地处理xaml中的所有内容。我决定把它转换成这样的C代码:

    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);
    }
    

    但这条线 B.Triggers.Add(A); 给出错误 System.InvalidOperationException: 'Triggers collection members must be of type EventTrigger.' 我怎样才能解决这个问题? 这种转变的提议是改变 To 财产 DoubleAnimation 在运行时。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Emond    6 年前

    问题中的代码没有完全反映xaml:缺少样式。

    我重新命名了一些变量,以使其更易于阅读(并防止像这样的错误)

    顺便说一下:righttoleftanimation应该命名为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;
    }