Wednesday, April 13, 2011

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!

From stackoverflow
  • 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>
    
  • oh... sorry, i've the doble quotes in my code. I Wrote this too quickly.

    I still have the problem... :(

  • 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>
    
    Greg D : These are the two options that exist for styling in WPF.
  • 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.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.