0

所以,这是我的 XAML 代码:

<UserControl x:Class="TugasBesarTAM_Moses_1072089.Brick01"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         Width="10" Height="5" Keyboard.KeyDown="UserControl_KeyDown">
<Canvas>
    <Rectangle x:Name="Brick" Fill="YellowGreen"
               Stroke="Black" StrokeThickness="1"
               Width="20" Height="10"
               Canvas.Left="-10" Canvas.Top="-5"
               RenderTransformOrigin="0.5 0.5" MouseLeftButtonDown="Brick_MouseLeftButtonDown">
        <Rectangle.RenderTransform>
            <TransformGroup>
                <ScaleTransform x:Name="Scale"/>
            </TransformGroup>
        </Rectangle.RenderTransform>

        <Rectangle.Resources>
            <Storyboard x:Key="sbdFade" Storyboard.TargetName="Scale">
                <DoubleAnimation To="3" Duration="0:0:0.5" BeginTime="0:0:0" Storyboard.TargetName="Scale" Storyboard.TargetProperty="ScaleX"/>
                <DoubleAnimation To="3" Duration="0:0:0.5" BeginTime="0:0:0" Storyboard.TargetName="Scale" Storyboard.TargetProperty="ScaleY"/>
                <DoubleAnimation x:Name="Opacity" To="0" Duration="0:0:0.5" Storyboard.TargetName="Brick" BeginTime="0:0:0" Storyboard.TargetProperty="Opacity" Changed="Opacity_Changed" />
            </Storyboard>
        </Rectangle.Resources>
    </Rectangle>
</Canvas>

我想通过下面的 c# 代码调用 sbdFade 故事板

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;

namespace TugasBesarTAM_Moses_1072089
{
/// <summary>
/// Interaction logic for Brick01.xaml
/// </summary>
public partial class Brick01 : UserControl
{
    public Brick01()
    {
        InitializeComponent();
    }

    private void BallHit()
    {
        Storyboard storyBoard = FindResource("sbdFade") as Storyboard;

        storyBoard.Begin();
    }

    private void Brick_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        BallHit();
    }
}

但是当我左键单击用户控件时,ResourceReferencekeyNotFoundException 弹出,导致我的故事板为空。

我不知道错误出在哪里,因为 xaml 和 c# 中的资源键是相同的。

有人注意到我的错误吗?谢谢。

编辑:注意:我也尝试过下面的代码(BallHit 方法),但无论哪种方式都会弹出相同的异常

private void BallHit()
{
    Storyboard storyBoard = (Storyboard)FindResource("sbdFade");

    storyBoard.Begin();
}
4

1 回答 1

0

您不是在Rectangle的资源中搜索,而是在 的资源中搜索UserControl,试试这个:

Storyboard storyBoard = Brick.FindResource("sbdFade") as Storyboard;
storyBoard.Begin();
于 2012-11-15T10:00:48.930 回答