如何在XAML中淡出特定的Rectangle对象? (不知道它将是哪一个)

时间:2011-01-04 22:29:36

标签: xaml animation windows-phone-7 storyboard

我加载了混合并选择矩形#1(有6个)并创建了一个简单的淡出故事板。

如何以编程方式轻松地将该Storyboard应用于其他矩形?

我希望我能说出像

这样的话

Storyboard.TargetNameProperty = this.rect2;

并运行故事板,这将淡出矩形#2但

  

错误2无法隐式转换类型   'System.Windows.Shapes.Rectangle'到   'System.Windows.DependencyProperty'C:_Code \ WP7_SL_WStest \ wp7wstest \ Views \ GameTimer.xaml.cs 63 49 wp7wstest

我的XAML

<phone:PhoneApplicationPage.Resources>
    <Storyboard x:Name="StoryboardFadeOut">
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="rect1">
            <EasingDoubleKeyFrame KeyTime="0" Value="1"/>
            <EasingDoubleKeyFrame KeyTime="0:0:1" Value="0"/>
        </DoubleAnimationUsingKeyFrames>
    </Storyboard>
</phone:PhoneApplicationPage.Resources>

1 个答案:

答案 0 :(得分:1)

您必须使用附加财产Storyboard.SetTargetName。实施例

<Rectangle Name="rect1" IsHitTestVisible="True" Fill="Green"
           MouseEnter="rect_MouseEnter"
           MouseLeave="rect_MouseLeave"/>
<Rectangle Name="rect2" IsHitTestVisible="True" Fill="Red"
           MouseEnter="rect_MouseEnter"
           MouseLeave="rect_MouseLeave"/>

代码

private void rect_MouseEnter(object sender, MouseEventArgs e)
{
    Rectangle clickedRectangle = sender as Rectangle;
    Storyboard StoryboardFadeOut = this.FindName("StoryboardFadeOut") as Storyboard;
    Storyboard.SetTargetName(StoryboardFadeOut, clickedRectangle.Name);
    StoryboardFadeOut.Begin();
}
private void rect_MouseLeave(object sender, MouseEventArgs e)
{
    Storyboard StoryboardFadeOut = this.FindName("StoryboardFadeOut") as Storyboard;
    StoryboardFadeOut.Stop();
}

更新

正如decyclone指出的那样,当我们直接访问Target时,最好使用SetTarget。更新的MouseEnter方法看起来像这样

private void rect_MouseEnter(object sender, MouseEventArgs e)
{
    Storyboard StoryboardFadeOut = this.FindName("StoryboardFadeOut") as Storyboard;
    Storyboard.SetTarget(StoryboardFadeOut, sender as DependencyObject);
    StoryboardFadeOut.Begin();
}