问题
I want to apply a default style for all the Button
s in a WPF app. This test app has two Window
s, 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