C# 如何将XAML代码从窗口移动到应用程序。参考资料

C# 如何将XAML代码从窗口移动到应用程序。参考资料,c#,wpf,vb.net,C#,Wpf,Vb.net,下面的xaml代码在窗口中运行良好 <Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Triggers> <

下面的xaml代码在窗口中运行良好

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Triggers>
    <EventTrigger RoutedEvent="Loaded">
        <BeginStoryboard>
            <Storyboard Duration="00:00:2" Storyboard.TargetProperty="Opacity">
                <DoubleAnimation From="0" To="1"/>
            </Storyboard>
        </BeginStoryboard>
    </EventTrigger>
</Window.Triggers>

我的WPF应用程序中有五个WPF窗口

我不想把上面的代码放到每个WPF窗口中


那么,如何将上述代码放入Application.Resources中才能在5个窗口中工作?

首先,让我们从触发器中开发一种合适的
样式:

<Style TargetType="{x:Type Window}">
    <Style.Triggers>
        <EventTrigger RoutedEvent="Loaded">
            <BeginStoryboard>
                <Storyboard Duration="00:00:2" Storyboard.TargetProperty="Opacity">
                    <DoubleAnimation From="0" To="1"/>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Style.Triggers>
</Style>

此样式可以放置在应用程序资源中

现在的问题是,您的窗口不使用资源中的默认样式,因此需要明确应用它(有关更多详细信息,请参阅)


<Window ... Style="{StaticResource {x:Type Window}}">