Why style is not applied when I'm removing StartupUri in WPF?

我的未来我决定 提交于 2019-12-24 07:39:45

问题


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>

So I've defined the global style in 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>

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

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.

What's the deal here?

Edit

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


回答1:


You can create your windows in the Startup handler.

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


来源:https://stackoverflow.com/questions/58017438/why-style-is-not-applied-when-im-removing-startupuri-in-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!