views:

36

answers:

3

Hey all,

Is there a way to setup global styles for my WPF application? What I'm hoping to do is apply a style to all my Buttons that also have an Image child.

Thanks in advance, Sonny

+2  A: 

You can do implicit styles in WPF which are applied by type

for instance

<Style TargetType="Button">

Will be applied to ALL the buttons within the scope of that style (If the style is in App.XAML it will apply to all buttons, if it is lower in the chain it will apply to all buttons underneath it)

If you want to apply it to only certain types of buttons (say imagebuttons) create a type that derives from button (call it ImageButton) and then create a style targeted to that type.

Foovanadil
OK... this sort of works. One of my buttons seems to respect this change, but the others do not. They all work if I give the style an `x:Key` and then call it explicitly from each button by using `Style="{StaticResource DisabledButton}"`. Any way I can avoid having to add an explicit reference to each button?
Sonny Boy
Make sure the resource dictionary where this style is defined is within scope for all buttons that you need to have the style applied to.Placing this style in App.xaml will be visible to all buttons in the app. Moving lower will restrict it's visibility.
Foovanadil
+1  A: 

Put the style into a ResourceDictionary tag inside your App.xaml and it will apply to the entire app.

samkass
+2  A: 

Well, sort of - it's a catch-all approach you can do - put the following element in your App.xaml - all your buttons will change (except the ones you apply a style to, manually).

<Style TargetType="{x:Type Button}">
    <Setter Property="Background" Value="LightPink"/> <!-- You should notice that one... -->
</Style>

However, if you want to hit only buttons with images - you have to inherit from Button everytime you do and then apply a style like this:

public class CustomImageButton:Button{}
<Style TargetType="{x:Type local:CustomImageButton}">
    <Setter Property="Background" Value="LimeGreen"/>
</Style>
<local:CustomImageButton Content="ClickMe"/>

It is a very coarse-grained global styling - and you need to follow the convention to make it work.

An alternative is to use Themes - read more about that here.

Goblin