Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my WPF style work?

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.

like image 933
Bill Jeeves Avatar asked Aug 06 '10 16:08

Bill Jeeves


People also ask

What is WPF style?

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.

What is the purpose of templates in WPF?

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.


2 Answers

Workaround: Just define a Name for the Application object:

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

It worked for me!

like image 173
Ehsan Zargar Ershadi Avatar answered Oct 10 '22 17:10

Ehsan Zargar Ershadi


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....

like image 21
Dan Puzey Avatar answered Oct 10 '22 15:10

Dan Puzey