System.Xaml: Method calls from Xaml

Xaml is awesome. I am hearing lot of "yeah"s... So have you tried out the new System.Xaml stack in .NET 4.0. If you havent give it a shot. It new and improved ...

One of the guys on the Xaml team is Shree and I finally got him to write a post on System.Xaml... Bet you'll see more of him. So have fun reading his post below ...

Rob blogged about Referencing a Named Object in XAML2009. It opens up interesting scenarios like using markup extension to call a method on a named object. Yup, you heard it right. Method calls from XAML. But not exactly... You will have to write code to do it J

We are talking about XAML like,


   Topper="{Call students.GetTopper}"


where students is a named object and GetTopper is a method on it. To make this work, implement a markup extension called CallExtension. In the ProvideValue method of the markup extension, get a reference to an IXamlNameResolver service provider.

IXamlNameResolver nameResolver = (IXamlNameResolver)serviceProvider.GetService(typeof(IXamlNameResolver));

Name resolver has a Resolve method that looks up a given name in the current namescope. This works fine if this is a backward reference (i.e, CallExtension comes after the named object in xaml). Resolve will return null for a forward reference (i.e, named object comes after CallExtension), as the parser hasn’t seen the name yet. In that case, return the object returned by GetFixupToken as the value of ProvideValue. This tells the parser to call ProvideValue second time once the required name is seen.

object instance = nameResolver.Resolve(parts[0]);

if (instance == null)


    string[] names = new string[] { parts[0] };

    instance = nameResolver.GetFixupToken(names);

    return instance;


Once you get the named object, you can use reflection to invoke the GetTopper method. Hope you found this post useful.

Attached is the complete project

Share this post