Search code examples
wpfwpf-animation

WPF - Animations in dynamically loaded XAML


I have standalone XAML files that are loaded dynamically into a MainWindow. The XAML files contain animation(s). It's simple to load XAML but what is the right way to get animations to work once the XAML is loaded. This is my test code which works correctly if pasted to a regular WPF window but if loaded dynamically the animation does not appear to start. I suspect a problem with a reference to TargetName and 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# code:

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

Solution

  • Insert below code after GridParent.Children.Add(wrapper);

    sb.Begin(window);
    window.Close();
    

    Otherwise you will get Namescope error.