【问题标题】:Call a storyboard declared in xaml from c#从 c# 调用在 xaml 中声明的情节提要
【发布时间】:2010-11-24 11:27:46
【问题描述】:

我正在尝试从 c# 调用在 xaml 中声明的情节提要。

<UserControl.Resources>
    <Storyboard x:Name="PlayStoryboard" x:Key="PlayAnimation">
        ...

我无法从代码隐藏文件中访问“PlayStoryboard”。任何想法我做错了什么?

【问题讨论】:

    标签: c# wpf xaml animation


    【解决方案1】:

    由于您将 Storyboard 声明为资源,因此可以使用 FindResource("PlayAnimation") 访问它。请参阅下面的示例:

    XAML:

    <Window x:Class="StackOverflow.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:StackOverflow"
            Title="MainWindow" Height="350" Width="525">
        <Window.Resources>
            <Storyboard x:Key="PlayAnimation" Storyboard.TargetProperty="(Canvas.Left)">
                <DoubleAnimation From="0" To="100" Duration="0:0:1"/>
            </Storyboard>
        </Window.Resources>
    
        <Canvas>
            <Button x:Name="btn">Test</Button>
        </Canvas>
    </Window>
    

    代码隐藏:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }
    
        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Storyboard sb = this.FindResource("PlayAnimation") as Storyboard;
            Storyboard.SetTarget(sb, this.btn);
            sb.Begin();
        }
    }
    

    【讨论】:

    • 一定要有“using System.Windows.Media.Animation;”到位。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 2013-11-10
    • 2013-03-28
    • 2012-08-09
    相关资源
    最近更新 更多