2

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

1 回答 1

1

在后面插入下面的代码GridParent.Children.Add(wrapper);

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

否则你会得到 Namescope 错误。

于 2015-12-16T15:35:23.167 回答