(Lviv community of .NET developers)

Markup Extensions

October 22, 2007 13:36 by rat

First of all, what is this misterious thing, MarkupExtension? As it follows from it's name, this is some kind of the extension for the XAML markup syntax, and in our case that is an the extension that allows user to shorten or simplify some operations in XAML, or at least provide some non-string data in case TypeConverter can not be used. One of the most common examples of the MarkupExtension is a shortened declaration of a data binding, like {Binding Path}. {StaticResource key} is also widely used, and that is also a MarkupExtension. Both of them can be declared in element syntax, but that is not widely used because the amount of XAML needed in such case is a bit larger, so I will use attribute syntax in my samples.


 In general, MarkupExtension is an object that is created by the XAML reader when it finds some construction like {ExtensionName Param1, param2,... } in object's attributes in XAML (or if we use the element syntax for the property values, than xaml reader just searches for the class with the specified name, but with an Extension word at the end). For example, such property value like Property="{Binding Value}" in XAML will be treated like this:

BindingExtension extension = new BindingExtension( Value );
someobj.Property = extension.ProvideValue( ... some service provider here... );

Here is a short sample of a simple markup extension:

namespace sample  
{  
    public class TestExtension : MarkupExtension  
    {  
        private string m_text;  
 
        public TestExtension( string text )  
        {  
            m_text = text;  
        }  
 
        public override object ProvideValue( IServiceProvider serviceProvider )  
        {  
            return m_text;  
        }  
    }  
An extension from this sample can be used in this way:
<Window xmlns:local="clr-namespace:sample">  
    <TextBlock Text="{local:Test text_to_print}"/>  
Window> 

As you could notice, parameters, that are passed in XAML after the name of the markup extension, are passed as a parameters to the most suitable constructor of the extension class. Also you can assign extension's properties in a way like this: {Extension Property1=data data data, Property2=data1 data1 data1}. All constructor parameters and property setters are separated with commas, so the values for them can contain spaces.

There is one case when the usage of the markup extension with element syntax can be extremely usefull. That is a case when extension should accept unknown count of the data of unknown type, like x:Array extension does.
Here is how it can be used:

<x:Array Type="typeName">  
  <arrayObject1/> 
  <arrayObject2/> 
  ...  
x:Array> 

You can add support for such functionality into your own markup extension by supporting IAddChild interface - XAML reader understands that as an ability to contain sub-elements inside the extension object.

So now you know what is a MarkupExtension (you can also look for information about it in MSDN article). But there are two more things, related to markup extensions, that you do not know about yet: MarkupExtensionReturnType attribute and the list of the services that are provided by the service provider that is passed in a ProvideValue method.

MarkupExtensionReturnType

MarkupExtensionReturnType attribute is used to determine the type of the value that is supposed to be returned by the extension. This is needed just for compilation-time checks and does not have any influence on the runtime.

Here is an example of the usage of the attribute:

namespace sample  
{  
    [MarkupExtensionReturnType(typeof(int))]  
    public class TestExtension : MarkupExtension  
    {  
        private string m_text;  
 
        public TestExtension( string text )  
        {  
            m_text = text;  
        }  
 
        public override object ProvideValue( IServiceProvider serviceProvider )  
        {  
            return int.Parse(m_text);  
        }  
    }  
Such extension can be used only the property accepts integers as a value.

Services

By default, the following services are supported: IProvideValueTarget, IXamlTypeResolver, IUriContext and IFreezeFreezables.
All of them can be accessed via serviceProvider in a following way: IProvideValueTarget target = (IProvideValueTarget)serviceProvider.GetService( typeof(IProvideValueTarget) );

Here are some details on every of the supported services:

  • IProvideValueTarget
    Used to provide the information on the target object and target property for the markup extension.
    Example:
    IProvideValueTarget target = (IProvideValueTarget)serviceProvider.GetService( typeof(IProvideValueTarget) );  
    // Outputs an object, that own the property, the result of ProvideValue method is about to be assigned to.  
    Debug.WriteLine( target.TargetObject, "Target object" );   
    // Outputs the description of the target property. PropertyInfo class is used to describe the property.  
    Debug.WriteLine( target.TargetProperty, "Target property" ); 
  • IXamlTypeResolver
    Such type resolver is used to find the desired type by it's name. It is used in x:Type extension to resolve types by their names, like Brush or local:MyType.
    Example:
    IXamlTypeResolver service = serviceProvider.GetService( typeof( IXamlTypeResolver ) ) as IXamlTypeResolver;  
    Type type = service.Resolve( "Brush" ); // In this case Brush type will be returned. 
  • IUriContext
    Used to determine the URI of the object, in context of which an extension is used. In most cases that is a path to the XAML file, where the particular instance of the extension is used. For examle it can be pack://application:,,,/App1;component/window1.xaml
    Example:
    IUriContext target = (IUriContext)serviceProvider.GetService( typeof( IUriContext ) );  
    Debug.WriteLine( target.BaseUri ); 

In the next article I will provide some usefull markup extensions that can make the life of the WPF developer a bit easier.


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags: ,
Categories: WinFx
Actions: Permalink | Comments (33) | RSSRSS comment feed

Comments

January 17. 2010 20:29

Do not turn back when you are just at the goal.

instant advance

March 19. 2010 22:14

Such a well versed blog, glad to see these are still around.

wrought iron furniture

April 6. 2010 20:44

Everything in this blog is completely true! In addition you've created an excellent blog post once again! Your writing style about development is impeccable, I really enjoy the articles. I check your site regularly and enjoy the fact its popular and has frequent users, please post about development more often.

Mc Hammer

April 15. 2010 07:20

Its nice to see such good information. I found your blog on Yahoo. I look forward to more posts.

research paper

April 24. 2010 20:42

A police officer in a small town stopped a motorist who was speeding down Main Street. "But officer." the man began, "I can explain,". "Just be quiet," snapped the officer. "I'm going to let you cool your heels in jail until the chief gets back..." "But officer, I just wanted to say...." "And I said to keep quiet! You're going to jail!" A few hours later the officer looked in on his prisoner and said, "Lucky for you that the chief is at his daughter's wedding. He'll be in a good mood when he gets back." "Don't count on it," answered the fellow in the cell. "I'm the groom."

dollar stores

May 6. 2010 13:01

Thanks for offering the facts.

microsoft points generator

May 12. 2010 08:22

Interesting article. Were did you got all the information from? Anyway thank you for this great post!

colon cleansing reviews

May 24. 2010 15:28

IMPORTANCE OF SEX : every couple should have this created by experienced psychics to help couples to enjoy their life.While sex may not be a significant

Whats the importance of sex in the life

May 25. 2010 21:11

Thanks for the share mate, I really appreciate your effort, now to start going to your links. I just bookmarked it but how do I get your RSS feeds to work with my browser(Chrome)? Keep up the good work!

term paper

June 22. 2010 16:51

I learn some new stuff from your blog. I wanted to say many thanks to you with regard to this fantastic post!

Jordan AJF8

July 4. 2010 15:45

This is easier and surely gives comfort to us. I will bookmark your blog and have my friends check up here often. Thanks!

Nike Shox NZ

July 6. 2010 16:25

Its outstanding, seeking in the time and work you place into your weblog and detailed facts you produce. I'll bookmark your web site and go to it weekly for the new posts.

Rerto Jordans

July 6. 2010 19:54

I found this very helpful. I have been learning the ropes on my own and taking advice wherever I can get it.

admission essay sample

July 6. 2010 23:30

it seems to be nice collection of plus size clothes since many of my friends are plus size and she didn’t find there choice of clothes so i think it would be nice option for them.

football socks

July 7. 2010 00:24

As everybody understands respect is essentially the most significant amongst people's existence. Only respect one another to have along nicely and I consider that leaving one's opinion is often a behavior of respect. Do you feel so?

supra skytop

July 7. 2010 06:40

Couldn't agree more.

Peel

July 7. 2010 17:44

One more good post, usually awesome to go through a great post over a topic you truly care about.

Mindy Pee

July 7. 2010 19:40

Great post and hi from Georgia

color name tags

July 8. 2010 05:56

Might you be interested to be website link partners?

free credit card numbers

July 8. 2010 19:17

Looks so good! Worth the wait :o)

Jordan AJF8

July 8. 2010 19:40

I want to thank you for this informative read, I would like to read more of your blogs and to share my thoughts with you.

creative recreation

July 9. 2010 03:46

Thanks for very interesting post

Bad Faith Law

July 11. 2010 21:06

I have been reading your post regularly. They are highly informative and helpful.

Rerto Jordans

July 14. 2010 22:07

Everything in this blog is completely true! In addition you've created an excellent blog post once again! Your writing style about development is impeccable, I really enjoy the articles. I check your site regularly and enjoy the fact its popular and has frequent users, please post about development more often.

vibram fivefingers

July 15. 2010 01:34

Greetings from California

reusable name badges

July 15. 2010 18:55

Hey, verify out this webpage have been you may Xbox 360 games, components and points for totally no cost! All you could have to carry out is sign up and complete some surveys and you are set. It's 100% risk-free and free! www.FreeGamesFor360.com

free

July 16. 2010 13:21

After browsing for a legitimate hotmail password hack system, I observed this application. Be cautious with it though, I don't know if it really is legal to use it to hack someones hotmail or yahoo account password, its only legal to make use of it oneself in circumstance you neglect the password. http://www.hotmailpasswordhack.net

hotmail password

July 16. 2010 16:13

Hey, examine out this site had been you can Xbox 360 games, components and points for positively zero cost! All you can have to do is sign up and complete some surveys and you are set. It is 100% risk-free and free! www.FreeGamesFor360.com

xbox 360

July 17. 2010 05:09

Thanks for the write up! This is really some great stuff here! Wishing for a following post for the similar subject.

Retro Jordans

July 17. 2010 05:15

This site is indeed a value adding one...

Jordans 6

July 18. 2010 06:45

Hey, For some reason when I put your feed into my RSS aggregator, it's not working. Can I get the RSS URL to ensure I'm using the right one? I appreciate it. :)

Dawn Trumpp

July 23. 2010 06:05

This article is precise and justify the time it will consume while reading it. I will recommend every one searching this topic must have a look on this post.

Air force one

July 30. 2010 02:02

This is a really good read for me. Your are one of the best bloggers I ever saw. Thank you for sharing. Welcome to our website. http://www.airjordan.cc/air-jordan-1-1/

Jordan 1

Add comment


(Will show your Gravatar icon)