WPF - 动态加载的XAML中的动画

时间:2015-12-11 15:21:23

标签: wpf wpf-animation

我有独立的XAML文件,它们动态加载到MainWindow中。 XAML文件包含动画。加载XAML很简单,但加载XAML后动画才能正常工作的正确方法是什么。这是我的测试代码,如果粘贴到常规WPF窗口,它可以正常工作,但如果动态加载,动画似乎不会启动。我怀疑对TargetName和TargetProperty的引用存在问题。

XAML:

<Window 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Page1" Width="1080" Height="1920">


    <Grid x:Name="GridWrapper">
        <Viewbox x:Name="ViewboxWrapper">
            <Grid x:Name="GridMain" Width="1080" Height="1920" Background="Black">
                <Grid.Resources>
                    <Storyboard x:Key="StoryboardPhotos" Duration="0:0:5">
                        <DoubleAnimation Storyboard.TargetName="LabelPhoto_01" Storyboard.TargetProperty="Opacity" BeginTime="0:0:0" Duration="0:0:5" To="1.0"></DoubleAnimation>
                    </Storyboard>
                </Grid.Resources>
                <Grid.RowDefinitions>
                    <RowDefinition Height="100*"></RowDefinition>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="100*"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <Label x:Name="LabelPhoto_01" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource StyleLabelPhoto}" Opacity="0">
                    <Image x:Name="ImagePhoto_01" Source="../../../Content/FPO/1.jpg"></Image>
                </Label>
            </Grid>
        </Viewbox>
    </Grid>
</Window>

C#代码:

 private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            Window window = null;
            using (FileStream fs = new FileStream("Templates/16x9/Portrait/1.xaml", FileMode.Open, FileAccess.Read)) //load xaml file
            {
                window = (Window)XamlReader.Load(fs);
            }

            Viewbox wrapper = (Viewbox)window.FindName("ViewboxWrapper");
            Grid mainGrid = wrapper.FindName("GridMain") as Grid;
            var sb = (Storyboard)mainGrid.FindResource("StoryboardPhotos"); 

            //disconnect grid from the parent window
            ((Grid)wrapper.Parent).Children.Remove(wrapper);

            // attach the grid to the main window
            GridParent.Children.Add(wrapper);
            sb.Begin();
        }

1 个答案:

答案 0 :(得分:1)

GridParent.Children.Add(wrapper);

之后插入以下代码
sb.Begin(window);
window.Close();

否则您将收到Namescope错误。

相关问题