Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

.NET

Properties, Dependency Properties, and WPF


A Stack of Text

In a WPF program, properties can be set in a variety of ways. They can be set explicitly through code or markup, they can be set through data bindings, they can be set through animations or styles, and they can be set in other ways beyond the scope of this article. Listing One is a XAML file named "PropertySettingsDemo.xaml" that provides a glimpse into this flexibility. If you're running Windows Vista or the .NET Framework 3.0 under Windows XP, you can simply launch this file as if it were a program, and it runs in your web browser. It contains two animations, so what you'll see might look something like Figure 1.

<!-- PropertySettingsDemo.xaml by Charles Petzold -->

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      WindowTitle="Property Settings Demo"
      Title="Property Settings Demo"
      FontSize="36pt">
    <!-- Resources -->
    <Page.Resources>
        <Style x:Key="styleTextBlock" TargetType="TextBlock">
            <Setter Property="FontSize" Value="24" />
            <Setter Property="Foreground" Value="Red" />
            <Setter Property="HorizontalAlignment" Value="Center" />
        </Style>
    </Page.Resources>

    <DockPanel>
        <ScrollBar Name="scroll"
                   DockPanel.Dock="Left"
                   Orientation="Vertical"
                   Minimum="10" Maximum="100" Value="20" />

        <!-- StackPanel with six TextBlock elements -->
        <StackPanel>
            <TextBlock Text="Hello XAML #1" FontSize="16" 
                       HorizontalAlignment="Center" />
            <TextBlock Text="Hello XAML #2" FontSize="12"
                       Name="txtblk2" HorizontalAlignment="Center" />
            <TextBlock Text="Hello XAML #3"
                       HorizontalAlignment="Center" />
            <TextBlock Text="Hello XAML #4" Name="txtblk4">
                <TextBlock.LayoutTransform>
                    <RotateTransform />
                </TextBlock.LayoutTransform>
            </TextBlock>
            <TextBlock Text="Hello XAML #5"
                   FontSize="{Binding ElementName=scroll, Path=Value}"
                       HorizontalAlignment="Center" />
            <TextBlock Text="Hello XAML #6" 
                       Style="{StaticResource styleTextBlock}" />
        </StackPanel>
    </DockPanel>

    <!-- Animations -->
    <Page.Triggers>
        <EventTrigger RoutedEvent="Page.Loaded">
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation Storyboard.TargetName="txtblk2"
                                Storyboard.TargetProperty="FontSize"
                                To="48" Duration="0:0:2"
                                AutoReverse="True" 
                                RepeatBehavior="Forever" />
                    <DoubleAnimation Storyboard.TargetName="txtblk4"
                                 Storyboard.TargetProperty=
                                     "LayoutTransform.Angle"
                                     To="360" Duration="0:0:10"
                                     RepeatBehavior="Forever" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Page.Triggers>
</Page>
Listing One

Figure 1: Animations generated by PropertySettingsDemo.xaml.

In the center of the PropertySettingsDemo.xaml file are six TextBlock elements, five of which have their FontSize properties set in five different ways. (The rotating TextBlock is just a gratuitous bonus, but I use it to make a point.) TextBlock is a relatively simple element used to display chunks of text. The six TextBlock elements are grouped as children in a StackPanel element, which stacks its children vertically. The StackPanel is itself a child (along with a ScrollBar) of a DockPanel, which is a child of the top-level element, a Page.

Notice first that the whole program contains no explicit coordinate positions or sizes except for the FontSize property itself. Each TextBlock is entirely capable of determining what size it needs to be, and the StackPanel can arrange these six elements based on those sizes. Also notice that StackPanel's arrangement of the elements dynamically accommodates the animations.

  • The first TextBlock element is assigned an explicit FontSize value of 16. In the WPF, values such as this are in units of 1/96 inch, which isn't exactly an industry standard of any sort except that video displays under Windows commonly use a resolution of 96 DPI. The value of 16 translates to 1/6 inch or 12 points.
  • The second TextBlock element is assigned a FontSize of 12, but it's used only as a base value for the first of the two animations. The animation takes the FontSize up to a value of 48 over two seconds, then back down over the next two seconds, and repeats the process "forever."
  • The third TextBlock doesn't have a FontSize property set, which would normally cause the value to be set to its default, which might be 11 (under Windows XP) or 12 (under Vista). But notice that the top-level Page element has its own FontSize property set to 36 points. That value is inherited by any descendent TextBlock that doesn't have its local FontSize property set.
    You might imagine property inheritance happening in one of two ways. Perhaps the parent element pushes property values on the child. Whenever the parent detects that it's getting another child assigned to it, it sets the FontSize property of the child to its own FontSize property. Or maybe it's a pull mechanism, where the child detects when it's being assigned a parent, and then queries the parent's FontSize property.
    The problem with these two theories, however, is that neither DockPanel nor StackPanel implement the FontSize property, and they know nothing about the FontSize property. The inheritance of the FontSize property is effectively skipping two generations, so the mechanism is obviously more complex than simple push or pull logic might suggest.
  • For the fourth TextBlock, I considered having the animation change a ScaleTransform so the TextBlock would grow and shrink in size like the second one, but I decided to add a little variety and apply the animation to a RotateTransform.
  • The fifth TextBlock binds its FontSize property to the Value property of the ScrollBar docked at the left of the page. You can use the ScrollBar to change the FontSize to values between 10 and 100 units.
  • The sixth TextBlock sets its Style property to a Style object defined as a resource towards the top of the file. The style sets the FontSize property, as well as the horizontal alignment of the element and its color.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.