R – WPF: How to inherit property values to all child controls

foregroundpropertiesuser interfacewpfxaml

I have UserControls containing other controls. I want that if I set a Foreground color for the UserControl, all child controls automatically inherit it. I have the same problem with font style/size.

Can I set these properties somehow to auto/inherit? Is this possible to set all subcontrols without a loop?

Best Answer

You can you create resource dictionaries to define default styles globally.

You can also reference a resource dictionary or define a style in any object.

In either case those styles will apply to all child objects that don't have a style explicitly defined...

Example:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
    <!--Default styles that will apply to any object of the specified type (if it doesn't have style set locally)-->
    <Style TargetType="Label" >
        <Setter Property="FontWeight" Value="Bold"/>
        <Setter Property="Margin" Value="0"/>
        <Setter Property="Padding" Value="0"/>
    </Style>
</ResourceDictionary>