Why is my WPF style not working? [SOLVED]

Trying to put style in app.xaml. My app.xaml reads:

<Application x:Class="TestApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Application.Resources> <Style x:Key="TestStyle" TargetType="Button"> <Setter Property="Background" Value="Red"/> </Style> </Application.Resources> </Application> 

My XAML for the button is as follows:

 <Button Content="Click Me!" Style="{StaticResource TestStyle}" /> 

Everything looks fine in the designer, but when I run the code, it fails:

 Provide value on 'System.Windows.StaticResourceExtension' threw an exception. 

I looked at him for ages, but I can not understand the problem!

EDIT

It seems to have something in common with the application. If I copy my code to another new project, it works fine. The only difference is that the window is loaded using β€œStartupUri =" MainWindow.xaml. ”In what does not work, I load the window during App.Startup as follows:

 protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); new TestWindow().Show(); } 

DECISION

Problem detected - I did not have an InitializeComponent call. Styles now work in the final product, but not in the designer. I am going to ask a separate question about this.

+4
source share
4 answers

Workaround: Just provide a name for the Application object:

<Appendix x: Name = "Application" ...

It worked for me!

+4
source

Based on your edit: if you have StartupUri="MainWindow.xaml" in the original xaml, but (as the code snippet suggests) you really have a file called TestWindow.xaml , this can be a problem! Try changing it to StartupUri="TestWindow.xaml" in the source project ....

+1
source

You can try using {DynamicResource TestStyle}. Perhaps TestStyle has not been created yet when you apply it to Button.

0
source

try it...

 <Style x:Key="TestStyle" TargetType="{x:Type Button}"> <Setter Property="Background" Value="Red"/> </Style> 

usually in WPF, you want your TargetType to be of the form {x:Type ...}
in silverlight you would use TargetType="Button"

0
source

All Articles