Welcome to Pete Brown's 10rem.net

First time here? If you are a developer or are interested in Microsoft tools and technology, please consider subscribing to the latest posts.

You may also be interested in my blog archives, the articles section, or some of my lab projects such as the C64 emulator written in Silverlight.

(hide this)

XAML Tip: Setting Attached Properties from Code

Pete Brown - 29 March 2012

Recently, a reader asked how they should go about setting the Typography properties from code-behind.

The original question was about Silverlight, but the approach works in WPF, Windows 8 and more.

Given the following markup:

<StackPanel>
<TextBlock x:Name="OriginalText"
FontSize="72"
FontFamily="Gabriola"
Text="Hello World!" />

<TextBlock x:Name="ExampleText"
FontSize="72"
FontFamily="Gabriola"
Text="Hello World!" />
</StackPanel>

You can set an attached property such as Typography.StylisticSet5 by using the SetValue method like this:

private void SetTextOptions()
{
ExampleText.SetValue(Typography.StylisticSet5Property, true);
}

The SetValue method comes from the DependencyObject base class. Typography.StylisticSet5Property is the name of a dependency property - an attached property in this case. This could easily have been the Canvas.Left property, the Grid.Row property or any number of other attached properties. The resulting display looks like this:

image

Note how the second TextBlock has had the stylistic set applied to it.

This approach used the SetValue method of the dependency object. There's also another way:

private void SetTextOptions()
{
Typography.SetStylisticSet5(ExampleText, true);
}

This version uses the Set[dpname] method of the class which owns the property. Use the most convenient method. Both are equivalent.

I also cover dependency properties and attached properties in both of my Silverlight books, as well as in my upcoming Windows 8 XAML book.

           
posted by Pete Brown on Thursday, March 29, 2012
filed under:            

Comment on this Post

Remember me