xaml中的动画不起作用,但在代码中有效

时间:2015-08-27 19:44:42

标签: c# wpf xaml animation eventtrigger

在简单的WPF应用程序中,我的Animation有一个非常棘手的问题。 我有一个自定义Panel,附加了X和Y DependencyProperty,它提供了如何排列布局的信息。我有CustomControl名为MovableGameCharacter,我想在面板上设置动画的动画。 所以这是代码: 在xaml中:

<Style TargetType="{x:Type local:MovableGameCharacter}" BasedOn="{StaticResource gamecharacter}" x:Key="movablegamecharacter">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MovableGameCharacter}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <EventTrigger RoutedEvent="MoveRight">
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation Storyboard.TargetProperty="(local:GameBoardPanel.X)" To="100" From="10"
                                     Duration="0:0:1"/>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Style.Triggers>
</Style>

我的代码中的MovableGameCharacter只会引发与移动相关联的RoutedEvent之一。

public void Move(Direction d)
    {
        switch (d)
        {
            case Direction.Left:
                RaiseEvent(new RoutedEventArgs(MoveLeftEvent, this));
                break;
            case Direction.Up:
                RaiseEvent(new RoutedEventArgs(MoveUpEvent, this));
                break;
            case Direction.Right:
                RaiseEvent(new RoutedEventArgs(MoveRightEvent, this));
                break;
            case Direction.Down:
                RaiseEvent(new RoutedEventArgs(MoveDownEvent, this));
                break;
            default:
                break;
        }
    } 

事件定义如下(例如MoveRightEvent):

public static readonly RoutedEvent MoveRightEvent =
        EventManager.RegisterRoutedEvent("MoveRight", RoutingStrategy.Bubble, typeof(MovementEventHandler), typeof(MovableGameCharacter));

但是,我很惊讶它的工作原理(在构造函数中添加):

MoveRight += (x, e) => { BeginAnimation(GameBoardPanel.XProperty, new DoubleAnimation(100, new Duration(new TimeSpan(0, 0, 1)))); };

所以我可能在xaml中出错,但我不知道自己做错了什么。我读过我必须写

Storyboard.TargetProperty="(local:GameBoardPanel.X)"

用于附加属性,但它仍然无效。

0 个答案:

没有答案