本文介绍了为什么在 WPF 中删除 StartupUri 时不应用样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为 WPF 应用程序中的所有 Button 应用默认样式.这个测试应用有两个Window,它们定义了相同的UI,如下所示.

I want to apply a default style for all the Buttons in a WPF app. This test app has two Windows, both defining the same UI showing bellow.

<StackPanel Orientation="Vertical" Margin="10">
     <Button Content="Red Button Style" />
     <Button Content="Red Button Style" />
     <Button Content="Red Button Style" />
     <Button Content="Red Button Style" />
</StackPanel>

所以我在 App.xaml

<Application x:Class="GlobalStyles.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:GlobalStyles">
    <Application.Resources>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Height"
                    Value="30" />
            <Setter Property="MinWidth"
                    Value="180" />
            <Setter Property="FontSize"
                    Value="16" />
            <Setter Property="HorizontalAlignment"
                    Value="Center" />
            <Setter Property="Padding"
                    Value="8 0" />
            <Setter Property="Margin"
                    Value="4" />
            <Setter Property="Cursor"
                    Value="Hand" />
            <Setter Property="BorderThickness"
                    Value="2" />
            <Setter Property="BorderBrush"
                    Value="DarkRed" />
            <Setter Property="Foreground"
                    Value="White" />
            <Setter Property="Background"
                    Value="OrangeRed" />
        </Style>
    </Application.Resources>
</Application>

正如您所注意到的,我删除了 ApplicationStartupUri 属性,因为我在 OnStartUp() 处创建了两个窗口.

and as you've noticed I removed the StartupUri property of Application since I'm creating both windows at OnStartUp().

App.xaml.cs

      protected override void OnStartup(StartupEventArgs e)
      {
            base.OnStartup(e);

            new MainWindow().Show();
            new SecondaryWindow().Show();
      }

问题

样式不会在运行时应用(但它们在设计器上应用).现在,如果我将 StartUpUri 属性放在 App.xaml 中,那么它就可以工作了.

The Problem

The styles are not applying at runtime (but they do on the designer). Now if I place the StartUpUri property inside App.xaml then it works.

这里有什么交易?

如果 base.OnStartup(e) 调用从 OnStartup() 中删除,那么它可以工作.

If the base.OnStartup(e) call is removed from OnStartup(), then it works.

推荐答案

您可以在启动处理程序中创建您的窗口.

You can create your windows in the Startup handler.

private void App_OnStartup(object sender, StartupEventArgs e)
{
    new MainWindow().Show();
    new SecondaryWindow().Show();
}

这篇关于为什么在 WPF 中删除 StartupUri 时不应用样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 00:50