Bill Jeeves
Bill Jeeves

Reputation: 503

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.

Upvotes: 6

Views: 2317

Answers (4)

Ehsan Zargar Ershadi
Ehsan Zargar Ershadi

Reputation: 24833

Workaround: Just define a Name for the Application object:

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

It worked for me!

Upvotes: 6

Dan Puzey
Dan Puzey

Reputation: 34198

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

Upvotes: 1

Muad&#39;Dib
Muad&#39;Dib

Reputation: 29216

try this...

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

Upvotes: 0

ggarber
ggarber

Reputation: 8360

You can make a try with {DynamicResource TestStyle}. Maybe TestStyle is not yet created when you apply it to the Button.

Upvotes: 0

Related Questions