WPF-动态加载XAML中的动画



我有独立的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();
        }

GridParent.Children.Add(wrapper); 后插入以下代码

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

否则,您将得到Namescope错误。

相关内容

  • 没有找到相关文章

最新更新