views:

3041

answers:

4

I want to set the background property of all the usercontrols of my project.

I tried with

<style TargetType={x:Type UserControl}>
    <setter property="Background" Value="Red" />
</style>

It compiles but didn't work.

¿Any Idea? Thanks!

+1  A: 

I think you're missing some double quotes:

Try this:

<Window.Resources>
    <Style TargetType="{x:Type UserControl}">
        <Setter Property="Background" Value="Red" />
    </Style>
</Window.Resources>
<Grid>
    <UserControl Name="control" Content="content"></UserControl>
</Grid>
Nick Josevski
A: 

oh... sorry, i've the doble quotes in my code. I Wrote this too quickly.

I still have the problem... :(

+7  A: 

You can only set a a style to a specific class, so this will work (create a UserControl object, not very useful):

<Window.Resources>
    <Style TargetType="{x:Type UserControl}">
        <Setter Property="Background" Value="Red" />
    </Style>
</Window.Resources>
<Grid>
    <UserControl Name="control" Content="content"></UserControl>
</Grid>

But this doesn't (Create a class derived from UserControl):

<Window.Resources>
    <Style TargetType="{x:Type UserControl}">
        <Setter Property="Background" Value="Red" />
    </Style>
</Window.Resources>
<Grid>
    <l:MyUserControl Name="control" Content="content"></l:MyUserControl>
</Grid>

What you can do is either explicitly set the style using the Style property:

<Window.Resources>
    <Style TargetType="{x:Type UserControl}" x:Key="UCStyle">
        <Setter Property="Background" Value="Red" />
    </Style>
</Window.Resources>
<Grid>
    <l:MyUserControl Name="control" Content="content" Style="{StaticResource UCStyle}"></l:MyUserControl>
</Grid>

or create a style for each derived class, you can use BasedOn to avoid duplicating the style content:

<Window.Resources>
    <Style TargetType="{x:Type UserControl}" x:Key="UCStyle">
        <Setter Property="Background" Value="Red" />
    </Style>
    <Style TargetType="{x:Type l:MyUserControl}" BasedOn="{StaticResource UCStyle}" />
</Window.Resources>
<Grid>
    <l:MyUserControl Name="control" Content="content"></l:MyUserControl>
</Grid>
Nir
These are the two options that exist for styling in WPF.
Greg D
A: 

Nir: Thanks!! It was a very complete answer!!!

As a workarround, I created an usercontrol class, and apply the style in the code-behind constructor. Now all my usercontrols inherit from this class. It Works, but I don't consider it elegant, I prefer don't mix code-behind and presentation.