Trying to put a 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}" />
In the designer all looks OK but when I run the code it fails with:
Provide value on 'System.Windows.StaticResourceExtension' threw an exception.
I've stared at it for ages but can't spot the problem!
EDIT
It seems to be something to do with the application overall. If I copy my code into another fresh project it works fine. The only difference is that the window is loaded using the "StartupUri="MainWindow.xaml". In the one that doesn't work I load the window up during the App.Startup as follows:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
new TestWindow().Show();
}
SOLUTION
Found the problem - I was missing an InitializeComponent call. Now the styles work in the final product but not in the designer. I'm going to ask a separate question about it.
Styles provide us the flexibility to set some properties of an object and reuse these specific settings across multiple objects for a consistent look. In styles, you can set only the existing properties of an object such as Height, Width, Font size, etc. Only default behavior of a control can be specified.
The template connects the visual presentation of the control with the control's capabilities. Because you define a template in XAML, you can change the control's appearance without writing any code. Each template is designed for a specific control, such as a Button.
Workaround: Just define a Name for the Application object:
< Application x:Name="App" ...
It worked for me!
Based on your edit: if you've got StartupUri="MainWindow.xaml"
in the original xaml, but (as your code snippet suggests) you actually have a file called TestWindow.xaml
, this could be the problem! Try changing it to StartupUri="TestWindow.xaml"
in the original project....
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