System.Xaml: IAmbientPropertyProvider Sample

Another post from Shree 🙂

In my last post I showed an sample using IXamlNameResolver service provider. In this post I will introduce you to another new service provider in System.Xaml, the IAmbientPropertyProvider. IAmbientPropertyProvider enables access to ambient properties (marked with Ambient attribute) in the object tree under construction.

Assume that there is a Family type which is a collection of Person objects and both Family and Person have a Name property. Also assume that we want to specify the family name once in the Family object and have it automatically appended to all Person objects under the Family.

In the following XAML we want FullName markup extension to get the last name from the name of the family object and append it to the first name given as argument.




    <Person Name='{FullName John}' />

    <Person Name='{FullName Ryan}' />


To do this,

1.       Apply the Ambient attribute on the property which needs to be looked up during parsing. This is Family.Name property in our example.

2.       In the ProvideValue method of the markup extension, get an IAmbientPropertyProvider object by calling serviceProvider.GetService().

IAmbientPropertyProvider ambientProvider = (IAmbientPropertyProvider)serviceProvider.GetService(typeof(IAmbientPropertyProvider));

3.       Call GetFirstAmbientValue() method on the service provider. This method takes a XamlMemberBase (for Family.Name) as argument and returns an AmbientPropertyValue. It walks up the object tree and returns the first occurrence of the XamlMember.

AmbientPropertyValue ambientPropertyValue = ambientProvider.GetFirstAmbientValue(null, nameXamlMember);

4.       AmbientPropertyValue.Value contains the actual value of the requested ambient property.

I have also used IXamlSchemaContextProvider service provider in this example. IXamlSchemaContextProvider provides access to the schema context, from which the Family.Name XamlMember can be obtained by using xamlSchemaContextProvider.SchemaContext.GetXamlType(typeof(Family)).GetMember(“Name”)

Sample attached

Share this post

Comments (0)

Skip to main content