Jonathan
Jonathan

Reputation:

WPF UserControl Style

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!

Upvotes: 6

Views: 27940

Answers (2)

Nir
Nir

Reputation: 29614

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>

Upvotes: 24

Nick Josevski
Nick Josevski

Reputation: 4226

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>

Upvotes: 3

Related Questions