I am trying to set the default Style for every window in my WPF Windows application in my app.xaml. So far i have this in app.xaml:
<Application.Resources> <ResourceDictionary> <Style x:Key="WindowStyle" TargetType="{x:Type Window}"> <Setter Property="Background" Value="Blue" /> </Style> </ResourceDictionary> </Application.Resources>
I can get the window to appear with this style when running the app (but not in VS designer) by specifically telling the window to use this style via:
Style="{DynamicResource WindowStyle}
This works, but is not ideal. So how do I:
Thanks!
Put simply, where you declare a style affects where the style can be applied. For example, if you declare the style in the root element of your app definition XAML file, the style can be used anywhere in your app. If you declare the style in one of the app's XAML files, the style can be used only in that XAML file.
If you look at App. xaml class of your WPF application, you will see the following XAML code. Here the StartupUri sets the startup Window of an application. If you want to change the Startup window to some other window, just change this value.
When a Window is created at run-time using the Window object, it is not visible by default. To make it visible, we can use Show or ShowDialog method. Show method of Window class is responsible for displaying a window.
WPF is still one of the most used app frameworks in use on Windows (right behind WinForms).
To add on to what Ray says:
For the Styles, you either need to supply a Key/ID or specify a TargetType.
If a FrameworkElement does not have an explicitly specified Style, it will always look for a Style resource, using its own type as the key
- Programming WPF (Sells, Griffith)
If you supply a TargetType, all instances of that type will have the style applied. However derived types will not... it seems. <Style TargetType="{x:Type Window}">
will not work for all your custom derivations/windows. <Style TargetType="{x:Type local:MyWindow}">
will apply to only MyWindow. So the options are
.
<Application.Resources> <Style x:Key="MyWindowStyle"> <Setter Property="Control.Background" Value="PaleGreen"/> <Setter Property="Window.Title" Value="Styled Window"/> </Style> </Application.Resources> ... <Window x:Class="MyNS.MyWindow" Style="{StaticResource MyWindowStyleKey}"> ...
So I'd say explicitly specified styles are the least work. You can anyways change aspects of the Style centrally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With