0
votes

Is there a way to create a style in a WPF application that will override the style of the Window type for all windows?

ie;

<Style x:Key="{x:Type Window}"
   TargetType="{x:Type Window}" >
    <Setter Property="Background" Value="Black" />
</Style>

in App.xaml or a resource dictionary referenced in App.xaml.

1
I give up on this one. See this post for more info stackoverflow.com/questions/431940/…. Let me know if you manage to solve it.Phil

1 Answers

1
votes

Short answer is: it is not possible.

Explanation There are lots of similar questions: WPF Window Style not working at runtime
WPF window style not being applied
How to set default WPF Window Style in app.xaml?

TargetType in Styles doesn't manage derived types.

You are not creating the Window class but the class derived from it. If you created instance of the Window class, it should have the style applied.

Dim frm As New Window
frm.Show()

However, it does not work (at least in 4.0), the styles from my Application.xaml are not applied at runtime. Workarounds are:

Load a resource dictionary at runtime:

Dim app As Application = New Application()
Application.Current.Resources.MergedDictionaries.Add(Application.LoadComponent(New Uri("/MyProject;component/MainDictionary.xaml", UriKind.Relative)))

Create the style at runtime

Sub Main()
 Dim app As Application = New Application()
 Dim sty As Style
 sty = New Style With {.TargetType = GetType(Window)}
 sty.Setters.Add(New Setter With {.Property = Control.BackgroundProperty, .Value = Brushes.Red})
 Application.Current.Resources.Add(GetType(Window), sty)
 Dim frm As New Window
 frm.ShowDialog()
End Sub

And the window has desired background. I think this is a bug.