【问题标题】:Why does accessing my Storyboard x:Name work in Silverlight but not in WPF?为什么访问我的 Storyboard x:Name 在 Silverlight 中有效,但在 WPF 中无效?
【发布时间】:2010-10-15 10:16:23
【问题描述】:

以下 WPF 代码出现错误:名称 'zipButtonOut' 在当前上下文中不存在。

但是,正如我在这里演示的那样,相同的代码在 Silverlight 中工作:http://tanguay.info/web/index.php?pg=codeExamples&id=65

我必须对 WPF 代码做些什么才能访问 Window.Resources 中的情节提要?我也在 WPF UserControl 中尝试过,但遇到了同样的错误。

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

【问题讨论】:

    标签: wpf storyboard


    【解决方案1】:

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

    Storyboard zipButtonOut = (Storyboard)Resources["zipButtonOut"];
    

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

    using System.Windows.Media.Animation;
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2014-11-13
        • 2011-02-08
        • 1970-01-01
        • 1970-01-01
        • 2021-04-15
        • 2014-07-20
        • 2016-11-27
        • 2011-03-12
        • 2015-09-12
        相关资源
        最近更新 更多