从c#调用xaml中声明的故事板

Dav*_*nes 25 c# wpf animation xaml

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

<UserControl.Resources>
    <Storyboard x:Name="PlayStoryboard" x:Key="PlayAnimation">
        ...
Run Code Online (Sandbox Code Playgroud)

我无法访问代码隐藏文件中的"PlayStoryboard".我有什么想法吗?

ASa*_*nch 49

由于您将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>
Run Code Online (Sandbox Code Playgroud)

代码隐藏:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)