tags:

views:

27

answers:

3

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"&gt;
    <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();
}

EDIT

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.

A: 

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

gustavogb
That runs but then the style is not applied.
Bill Jeeves
A: 

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"

Muad'Dib
Doesn't help :(
Bill Jeeves
The two are equivalent at runtime. Using x:Type adds some compile time checking.
John Bowen
+1  A: 

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

Dan Puzey