在DataTemplate中设置Storyboard的目标

4
我希望能够在单击按钮时使用故事板展示一个平面投影动画的图片。当我尝试在单个实例上执行时,这一方法是有效的。但是在我的 Silverlight 页面(Windows Phone 7)中,我使用数据模板来从一组对象中重复此操作。然而,在这里,它并不起作用。以下是数据模板的 .xaml 内容:
                            <DataTemplate x:Name="MyDt">
                                <Button Tag="{Binding iId}" BorderThickness="0" Click="buttonClick" Width="456" Style="{StaticResource ButtonStyle}">
                                    <Image x:Name="MyImg" Source="Images/image.png" Visibility="Collapsed">
                                        <Image.Projection>
                                            <PlaneProjection/>
                                        </Image.Projection>
                                    </Image>
                                </Button>
                            </DataTemplate>

这是故事板的.xaml文件(在手机页面资源中):

    <Storyboard x:Name="storyboardShowImage">
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationY)" Storyboard.TargetName="">
            <EasingDoubleKeyFrame KeyTime="0" Value="90"/>
            <EasingDoubleKeyFrame KeyTime="00:00:01" Value="0"/>
        </DoubleAnimationUsingKeyFrames>
    </Storyboard>

这里是按钮点击事件的 .cs 代码:

private void buttonClick(object sender, RoutedEventArgs e)
    {
        /* Get image object from x:Name */
        Image img;
        img = GetChildImage((DependencyObject)sender, "MyImg");
        /* Launch storyboard on img object */
        ((DoubleAnimationUsingKeyFrames)storyboardShowImage.Children[0]).SetValue(Storyboard.TargetNameProperty, img.Name);
        storyboardShowImage.Begin();
    }

但是我遇到了错误:
Cannot resolve TargetName MyImg.

我认为问题在于有多个x:Name为"MyImg"的Image对象,但我不知道如何在数据模板中将故事板目标设置为正确的图像。
1个回答

3

它无法解析该名称,因为该名称仅适用于 DataTemplate 中。您可以将 Storyboard 移到 DataTemplate 中,以便可以将其应用于每个实例中的图像,并使用 VisualStateManager 在 Pressed 状态下启动动画;或者您可以在代码中创建 Storyboard 并相应地设置目标。


谢谢您的回答。我是新手,不太知道如何在DataTemplate中使用StoryBoard并通过VisualStateManager启动它。您有示例或链接吗? - TheFrancisOne
2
请查看此问题的已接受答案:https://dev59.com/hHA75IYBdhLWcg3wGU-I 您只需要在“Pressed”状态下进行更改,然后将按钮样式应用于数据模板中的按钮。 - Derek Lakin
谢谢提供链接。我尝试使用VisualState来更改启动故事板,但我希望在单击按钮时启动它,并且当我使用Expression Blend时,我只看到我的按钮的视觉状态:“Normal”,“MouseOver”,“Pressed”,“Disabled”。 - TheFrancisOne
是的,在手机上,“Pressed”和“Click”之间几乎没有什么区别 :) - Derek Lakin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接