1

xaml

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
    <StackPanel>
        <StackPanel.Resources>
            <Storyboard x:Name="myStoryboard">
                <DoubleAnimation Storyboard.TargetName="MyAnimatedRectangle" Storyboard.TargetProperty="Opacity" From="1.0" To="0.0" Duration="0:0:1" AutoReverse="True" RepeatBehavior="Forever" />
            </Storyboard>
        </StackPanel.Resources>
        <TextBlock Margin="10">Click on the rectangle to start the animation.</TextBlock>
        <Rectangle MouseLeftButtonDown="Mouse_Clicked" x:Name="MyAnimatedRectangle" Width="100" Height="100" Fill="Blue" />
    </StackPanel>
</Grid>
</Window>

vb

Private Sub Mouse_Clicked(ByVal sender As Object, ByVal e As MouseEventArgs)
    myStoryboard.Begin()
End Sub

c#

private void Mouse_Clicked(object sender, MouseEventArgs e)
{
    myStoryboard.Begin();
}

Error screen:

https://prnt.sc/jbeo16

Any support will be appreciated.

Thanks in advance

1 Answers1

4

As the error says, you need to define the x:Key directive associated with each resource.

<StackPanel x:Name="myStackPanel">
    <StackPanel.Resources>
        <Storyboard x:Key="myStoryboard">
            <DoubleAnimation Storyboard.TargetName="MyAnimatedRectangle" Storyboard.TargetProperty="Opacity" From="1.0" To="0.0" Duration="0:0:1" AutoReverse="True" RepeatBehavior="Forever" />
        </Storyboard>
    </StackPanel.Resources>
    <TextBlock Margin="10">Click on the rectangle to start the animation.</TextBlock>
    <Rectangle MouseLeftButtonDown="Mouse_Clicked" x:Name="MyAnimatedRectangle" Width="100" Height="100" Fill="Blue" />
</StackPanel>

Then get it from code-behind:

private void Mouse_Clicked(object sender, MouseEventArgs e)
{
    var myStoryboard = (Storyboard)myStackPanel.FindResource("myStoryboard");
    myStoryboard.Begin();
}

From docs:

Each resource in a resource dictionary must have a unique key. When you define resources in markup, you assign the unique key through the x:Key Directive.

What's the difference between x:Key and x:Name in WPF?

Vitali
  • 645
  • 9
  • 14