Implicit styling inside a container

I want to apply Padding="0"

to everyone Label

on the left sidebar (the first one StackPanel

) so that it is left aligned with each TextBox

(and other controls).

How can I define an implicit style in <ApplicationResources>

that only applies to elements in a particular container?

Alternative:

  • Use x:Key="sidebarLabel"

    . However, this setting seems overkill for many sidebar shortcuts in my actual application.
  • Add Padding=0

    to each Label

    in the sidebar. This is essentially the same as the previous alternative.
  • Move the implicit style to <StackPanel.Resources>

    . However, I want the styles (in App.xaml

    ) to be 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>

      

+3


source to share


1 answer


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 everything Label.Style

that is used inside a StackPanel

. If you prefer to show this behavior only for labels in a specific one StackPanels

, you can use 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 everyone StackPanels

with the help StaticResource LabelStyledPanel

uses the label style.

+3


source







All Articles