Search code examples
wpfxamlwpf-styleimplicit-style

Implicit Style Within Container


I want to apply Padding="0" to each Label on the left sidebar (the first StackPanel) so that it left-aligns with each TextBox (and other controls).

How can I define an implicit style in <ApplicationResources> which only applies to elements within a specific container?

Alternatives:

  1. Use x:Key="sidebarLabel". However, this option seems redundant for the many labels in the sidebar of my actual application.
  2. Add Padding=0 to each Label in the sidebar. This is essentially the same as the previous alternative.
  3. Move the implicit style into <StackPanel.Resources>. However, I want to keep the styles (in App.xaml) separate from the XAML (in MainWindow.xaml).

 

<Application.Resources>
    <Style TargetType="{x:Type Label}">
        <Setter Property="Padding" Value="0" />
    </Style>
</Application.Resources>      

 

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="2*"/>
    </Grid.ColumnDefinitions>

    <StackPanel Grid.Column="0">
        <GroupBox Header="New User">
            <StackPanel>
                <Label>First Name:</Label>
                <TextBox/>
                <Label>Last Name:</Label>
                <TextBox/>
            </StackPanel>
        </GroupBox>
    </StackPanel>
    <GroupBox Grid.Column="1" Header="Main">
        <StackPanel>
            <Label>I want default padding here</Label>
        </StackPanel>
    </GroupBox>
</Grid>

Solution

  • you can use Style.Resources in app.xaml like this:

    <Application.Resources>
        <Style TargetType="StackPanel">
            <Style.Resources>
                <Style TargetType="Label">
                    <Setter Property="Padding" Value="0" />
                </Style>
            </Style.Resources>
        </Style>
    </Application.Resources>
    

    this sets all Label.Style, that are used inside a StackPanel. If you like to provide this behaviour only to labels in specific StackPanels you can use a x:Key like this:

    <Application.Resources>
        <Style TargetType="StackPanel" x:Key="LabelStyledPanel">
            <Style.Resources>
                <Style TargetType="Label">
                    <Setter Property="Padding" Value="0" />
                </Style>
            </Style.Resources>
        </Style>
    </Application.Resources>
    

    then all StackPanels using StaticResource LabelStyledPanel use the label style.