Blog

Creating Dynamic Properties in XAML

By Ken Getz

Thumbnail for 594

Usually, the standard XAML property syntax provides the functionality you need. Sometimes, however, it's not possible to set the property value at design time-some properties require their values to be set dynamically, at runtime; others require the ability to set the property to an existing object. In these cases, you'll need to use a markup extension, which allows you to set property values in a non-standard way.

You can specify a markup extension either as a nested element, or as an attribute. When you use a markup extension as an attribute, it always must be surrounded by curly braces ({ }), indicating that XAML must supply the value at runtime.

For example, XAML supplies the Binding class, which allows you to bind a property of one object to a property of another. The Binding class provides several attributes that you can use to provide binding, but the ones you'll use in the example that follows are the ElementName and Path properties. ElementName allows you to supply the name of the object to which you want to bind, and Path supplies the property of the object to which you want to bind.

In order to bind a property of one object to a corresponding simple property of another object, you can use syntax like the following:

Property = "{Binding
ElementName=ObjectName, Path=PropertyName}"

You can express the same property binding in this way, using a child element:

<Object.Property>
<Binding ElementName="ObjectName" Path="PropertyName"/>
</Object.Property>

The attribute syntax, using curly braces, is simply a shortcut that represents the same XAML as the more verbose Parent.Property syntax.

This post is an excerpt from the online courseware for our Windows 8 Applications Using XAML: Apps and UI course written by expert Ken Getz.



Ken Getz

Ken Getz is a featured instructor for several of our Visual Studio courses. He is a Visual Basic and Visual C# expert and has been recognized multiple times as a Microsoft MVP. Ken is a seasoned instructor, successful consultant, and the author or co-author of several best-selling books. He is a frequent speaker at technical conferences like Tech-Ed, VSLive, and DevConnections and he has written for several of the industry's most-respected publications including Visual Studio Magazine, CoDe Magazine, and MSDN Magazine.


This blog entry was originally posted November 05, 2012 by Ken Getz

VideoWindows 8 AppsXAMLWindows 8