在多个控件中应用相同的故事板

时间:2012-06-04 17:01:34

标签: c# wpf

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="storyboard.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480">
<Window.Resources>
    <Storyboard x:Key="all_in_one">
        <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(GradientBrush.GradientStops)[3].(GradientStop.Color)" Storyboard.TargetName="btn_a">
            <EasingColorKeyFrame KeyTime="0" Value="#FFCDCDCD"/>
            <EasingColorKeyFrame KeyTime="0:0:0.6" Value="#FFED0B00"/>
            <EasingColorKeyFrame KeyTime="0:0:1" Value="#FFCDCDCD"/>
        </ColorAnimationUsingKeyFrames>
    </Storyboard>
</Window.Resources>


<Grid x:Name="LayoutRoot">
    <Button x:Name="btn_a" Content="A" HorizontalAlignment="Left" Height="56" Margin="117,134,0,0" VerticalAlignment="Top" Width="66" Click="btn_a_Click" />
    <Button x:Name="btn_b" Content="B" HorizontalAlignment="Left" Height="56" Margin="187,134,0,0" VerticalAlignment="Top" Width="66"/>
    <Button x:Name="btn_c" Content="C" Height="56" Margin="257,134,301,0" VerticalAlignment="Top"/>
</Grid>

enter image description here

这里我为按钮a(“btn_a”)创建了一个故事板。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        this.InitializeComponent();

        // Insert code required on object creation below this point.
    }

    private void btn_a_Click(object sender, RoutedEventArgs e)
    {
        Storyboard button_animation = (Storyboard)(FindResource("all_in_one"));
        button_animation.Begin();            
    }
}

我希望动态地将代码中的btn_b和btn_c等相同的故事板应用于相同的故事板。

如果我点击按钮b,它也必须设置动画和按钮c。

1 个答案:

答案 0 :(得分:0)

这可能不是最好的方法。话虽这么说,你可以这样做:

    private void btnC_Click(object sender, RoutedEventArgs e)
    {
        Storyboard storyboard = Resources["all_in_one"] as Storyboard;
        Storyboard.SetTargetName(storyboard, "btnC");

        storyboard.Begin();
    }

您需要从XAML中移除 Storyboard.TargetName 分配才能使其生效。

如果您需要一次启动多个故事板,只需在使用新目标名称调用Storyboard.SetTargetName函数后再调用Begin()。