将Silverlight动画绑定到按钮单击

时间:2010-10-25 19:40:10

标签: silverlight

我正试图点击一个按钮启动动画。以下代码看起来合理,但是会引发运行时错误。理想情况下,我只想将故事板指向一个命令。这是可能的(我用谷歌搜索,没有发现任何迹象表明它是)

                <Button Width="50" Height="24" Content="X">
                    <Button.Triggers>
                        <EventTrigger RoutedEvent="Button.Click">
                            <BeginStoryboard Storyboard="{StaticResource ShowTemplateSelector}">
                            </BeginStoryboard>
                        </EventTrigger>
                    </Button.Triggers>
                </Button>

这是故事板:

<UserControl.Resources>
    <Storyboard x:Name="ShowTemplateSelector">
        <DoubleAnimation Storyboard.TargetName="canvasStyleSelected" Storyboard.TargetProperty="Width" From="0" To="332" Duration="0:0:0.4" />
        <DoubleAnimation Storyboard.TargetName="canvasStyleSelected" Storyboard.TargetProperty="Height" From="0" To="100" Duration="0:0:0.4" />
    </Storyboard>

运行时错误说:

Microsoft JScript运行时错误:Silverlight应用程序中未处理的错误2531发生错误。 System.Windows.Application.LoadComponent(对象组件,Uri resourceLocator)中的[行:97位置:55]    在SilverlightApplication8.MainPage.InitializeComponent()    在SilverlightApplication8.MainPage..ctor()    在SilverlightApplication8.App.Application_Startup(Object sender,StartupEventArgs e)    在MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex,Delegate handlerDelegate,Object sender,Object args)    在MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj,IntPtr unmanagedObjArgs,Int32 argsTypeIndex,Int32 actualArgsTypeIndex,String eventName)

第97行是这样的:

<EventTrigger RoutedEvent="Button.Click">

3 个答案:

答案 0 :(得分:3)

您可以使用Blend SDK获得您想要的内容。只需将ControlStoryboardAction行为附加到按钮:

    <Button Width="50" Height="24" Content="X">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <ei:ControlStoryboardAction Storyboard="{StaticResource ShowTemplateSelector}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </Button>

其中i和ei的定义如下:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"

答案 1 :(得分:2)

您需要将故事板移动到触发器中。如果您尝试将其作为StaticResource引用,则无法解析ResourceDictionary的命名范围中的名称

<EventTrigger RoutedEvent="Button.Click">
  <BeginStoryboard>
    <BeginStoryboard.Storyboard>
      <Storyboard x:Name="ShowTemplateSelector">
        <DoubleAnimation Storyboard.TargetName="canvasStyleSelected" Storyboard.TargetProperty="Width" From="0" To="332" Duration="0:0:0.4" />
        <DoubleAnimation Storyboard.TargetName="canvasStyleSelected" Storyboard.TargetProperty="Height" From="0" To="100" Duration="0:0:0.4" />
      </Storyboard>
  </BeginStoryboard.Storyboard>
</BeginStoryboard>

答案 2 :(得分:-1)

改变这个......

<BeginStoryboard Storyboard="{StaticResource ShowTemplateSelector}">
</BeginStoryboard>

到此......

<BeginStoryboard Storyboard="{DynamicResource ShowTemplateSelector}">
</BeginStoryboard>