为什么访问我的故事板x:Name在Silverlight中有效,但在WPF中无效?

为什么访问我的故事板x:Name在Silverlight中有效,但在WPF中无效?,wpf,storyboard,Wpf,Storyboard,以下WPF代码获取错误:名称“zipButtonOut”在当前上下文中不存在。 但是,正如我在这里演示的,相同的代码在Silverlight中工作: 要在Window.Resources中访问情节提要,我必须对WPF代码做些什么?我也在WPF用户控件中尝试过,但得到了相同的错误 XAML: <Window x:Class="TestDataGrid566.Test1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/prese

以下WPF代码获取错误:名称“zipButtonOut”在当前上下文中不存在。

但是,正如我在这里演示的,相同的代码在Silverlight中工作:

要在Window.Resources中访问情节提要,我必须对WPF代码做些什么?我也在WPF用户控件中尝试过,但得到了相同的错误

XAML:

<Window x:Class="TestDataGrid566.Test1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Test1" Height="300" Width="300">
    <Window.Resources>
        <Storyboard x:Name="zipButtonOut" x:Key="zipButtonOut">
            <DoubleAnimation Storyboard.TargetName="buttonContinue"
Storyboard.TargetProperty="Width"
From="0" To="300" Duration="0:0:.2"></DoubleAnimation>
            <DoubleAnimation Storyboard.TargetName="buttonContinue"
Storyboard.TargetProperty="Height"
From="2" To="50" Duration="0:0:.4"></DoubleAnimation>
        </Storyboard>
    </Window.Resources>

    <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel HorizontalAlignment="Center" Margin="20">
            <Button x:Name="buttonBegin" Content="Click here to begin" Background="Green" Click="buttonBegin_Click"/>
            <Button x:Name="buttonContinue" Margin="0 70 0 0" Width="160" Height="2" FontSize="18" Background="Yellow"
Content="Click here to continue" Visibility="Collapsed"></Button>
        </StackPanel>
    </Grid>
</Window>
using System.Windows;

namespace TestDataGrid566
{
    public partial class Test1 : Window
    {
        public Test1()
        {
            InitializeComponent();
        }

        private void buttonBegin_Click(object sender, RoutedEventArgs e)
        {
            buttonBegin.Visibility = Visibility.Collapsed;
            buttonContinue.Visibility = Visibility.Visible;
            //zipButtonOut.Begin(); //GETS ERROR: The name 'zipButtonOut' does not exist in the current context.
        }
    }
}

我不知道为什么它可以在Silverlight中工作,但是在WPF中,您添加到资源集合的控件在代码隐藏中的x:Name中不可用。它们可以通过其x:Key通过资源集合进行访问,因此您可以删除x:Name属性,并在注释掉的代码行之前添加以下代码行,这样就可以了(当然,取消注释有问题的行):

请注意,这需要以下using语句:

using System.Windows.Media.Animation;

看起来VS Silverlight工具也为x:Name资源生成了一个“zipButtonOut”访问器。将来,只需查看obj文件夹中生成的文件(可能是“test1.g.cs”),就可以看到为x:Names生成了什么代码

using System.Windows.Media.Animation;