I can’t understand why happens this. I have a simple application in WPF. This application have a window, and in the App.xaml have defined one style, that changes the style of all the buttons:
<Application x:Class="PruebasDesk.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml">
<Application.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Height" Value="23"></Setter>
<Setter Property="Width" Value="75"></Setter>
<Setter Property="Background" Value="DarkCyan"></Setter>
</Style>
</Application.Resources>
</Application>
This works fine, all the buttons get the style. Now, here is the problem. If instead of using the StartupUri attribute to start the application, I start it with using the OnStartup method:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
Window1 win1 = new Window1();
win1.Show();
}
}
The buttons of the application don’t get applied the button style defined at App.xaml. But… if I add another style to the App.xaml, like this:
<Application x:Class="PruebasDesk.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<Application.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Height" Value="23"></Setter>
<Setter Property="Width" Value="75"></Setter>
<Setter Property="Background" Value="DarkCyan"></Setter>
</Style>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Height" Value="23"></Setter>
<Setter Property="Width" Value="180"></Setter>
<Setter Property="Background" Value="Azure"></Setter>
</Style>
</Application.Resources>
</Application>
Then the buttons get the style applied!!! This seems really weird to me. Does anyone know if I am missing something?
I can’t tell you with certainty why that behavior occurs but I can tell you that best practices would have steered you away from using
App.xamlin that fashion. What I believe to be a better practice is to only merge in your resource dictionaries in app.xaml. Storing the actual styles is a good way to create an unmanageable project.Create a new ResourceDictionary file and add those styles. Merge the dictionaries in as you add more of them.
Alternatively, you could hook into the event
Startup(app.xaml:Startup="App_Startup") and not overrideOnStartup. This will work with the App.xaml resource setup you have defined. It is likely a timing issue.