AlexPi
AlexPi

Reputation: 586

Apply a style to multiple controls without using a key

In .NET WPF, I have the following XAML code:

<StackPanel>
    <StackPanel.Resources>
        <Style TargetType="FrameworkElement">
            <Setter Property="Margin" Value="5" />
        </Style>
    </StackPanel.Resources>

    <CheckBox>Check 1</CheckBox>
    <TextBox>Some text...</TextBox>
</StackPanel>

The controls do not have any margins applied to them.

Is it possible to apply a style to multiple controls (of different types) without using a key to set the style explicitly on each control?

Upvotes: 1

Views: 245

Answers (2)

brunnerh
brunnerh

Reputation: 185489

Styles are not inherited, you can base the subclasses' styles on that one though using BasedOn.

Another method in this case should be using an ItemsControl with an ItemContainerStyle set to this style.

There are examples for both methods in this answer.

Upvotes: 1

erodewald
erodewald

Reputation: 1825

Sorry, I misread the question before I wrote this out. My answer is useful if you want to style multiple checkboxes within the StackPanel.

Implicitly style the entire application by placing this into your app.xaml's merged dictionaries.

<Style TargetType="CheckBox" BasedOn="{DynamicResource YourBaseStyle}"/>

This also works on a much smaller scope. Reducing the scope to just that StackPanel simply requires that you add that same line of code to your StackPanel.Resources tag.

Upvotes: 1

Related Questions