wpf - 为什么访问我的 Storyboard x :Name work in Silverlight but not in WPF?

标签 wpf storyboard

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

但是,相同的代码可以在 Silverlight 中运行,正如我在此处演示的:http://tanguay.info/web/index.php?pg=codeExamples&id=65

我必须对 WPF 代码执行什么操作才能访问 Window.Resources 中的 Storyboard?我也在 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.
        }
    }
}

最佳答案

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

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

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

using System.Windows.Media.Animation;

关于wpf - 为什么访问我的 Storyboard x :Name work in Silverlight but not in WPF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/681054/

相关文章:

ios - 在 Storyboard实例化的 View 之间进行通信

c# - 从另一个 View 模型访问 MainViewModel

c# - 如何在 ObservableCollection<T> 中使用 GetType 返回的类型?

wpf - 如何在 TextBox 上设置正则表达式?

ControlTemplate 的 ResourceDictionary 中的 WPF 事件

c# - 相对 URI 在 BitmapImage 中不起作用

ios - 为首次使用应用程序制作 View

ios - 在 Swift 中以编程方式完全杀死 ViewController

xcode - Storyboard预览与 xCode 6 中的模拟器或设备不匹配

ios - Storyboard] 如何先在 uiscrollview 上工作,然后再添加