错误:每个字典条目必须具有关联的密钥

时间:2018-04-28 22:01:27

标签: c# wpf vb.net xaml animation

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();
}

错误屏幕:

https://prnt.sc/jbeo16

任何支持将不胜感激。

提前致谢

1 个答案:

答案 0 :(得分:2)

如错误所示,您需要定义与每个资源相关联的x:Key指令。

<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>

然后从代码隐藏中获取它:

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

来自docs

  

资源字典中的每个资源都必须具有唯一键。什么时候   您在标记中定义资源,您可以通过分配唯一键   x:关键指令。

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