#1,040 – An Example of Dependency Property Inheritance

One of the attributes of dependency properties in WPF is that they support inheritance of property values within a tree of user interface elements.  Controls (dependency objects) within the tree that make use of a particular dependency property can set a property value locally or retrieve a value from an element higher up in the tree.  The local value takes precedence over the inherited value and then in turn applies to all elements “further down”.

(There are a number of other places from which a dependency property can get its value).

Below is an example.  FontSize is set to 20 for the top-level Window.  This value is use for lower-level elements unless they set their own value.  The GroupBox sets FontSize to 14, which then applies to it and elements under it.  Within the GroupBox, the second Label sets its own value for FontSize.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="Dependency Properties" 
        Width="280" Height="252"
        FontSize="20">

    <StackPanel Name="spOuter" 
                Margin="5">
        <Label Name="lbl1" Content="Label 1"/>
        <Label Name="lbl2" Content="Label 2"/>
        <GroupBox Name="gb1" Header="Stuff" FontSize="14">
            <StackPanel Name="spInner" Orientation="Horizontal">
                <Label Name="lbl3" Content="Label 3"/>
                <Label Name="lbl4" Content="Label 4" FontSize="10"/>
            </StackPanel>
        </GroupBox>
        <Button Name="btn1" Content="I'm a Button"
                            Padding="10,5" HorizontalAlignment="Center"
                            Click="btn1_Click"/>
    </StackPanel>
</Window>

1040-001
See this post for another example of dependency property inheritance.

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: