从 c# 调用在 xaml 中声明的故事板 [英] Call a storyboard declared in xaml from c#

查看:28
本文介绍了从 c# 调用在 xaml 中声明的故事板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 c# 调用在 xaml 中声明的故事板.

I am trying to call a storyboard declared in xaml from c#.

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

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

I dont have access to "PlayStoryboard" from the codebehind file. Any ideas what i am doing wrong?

推荐答案

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

Since you declared your Storyboard as a Resource, you can access it by using FindResource("PlayAnimation"). See sample below:

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

这篇关于从 c# 调用在 xaml 中声明的故事板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆