Click here to Skip to main content
15,886,137 members
Articles / Desktop Programming / WPF
Alternative
Tip/Trick

Markup Extension for Generic Classes

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
6 Feb 2015CPOL1 min read 13.7K   167   4  
This is an alternative for "Markup Extension for Generic classes"

Introduction

Declaring generic types in XML is something which is sadly lacking from the current incarnation of WPF. Although they are fully supported[^] in XML 2009[^], you cannot use these features in markup-compiled XAML or BAML.

Background

In .NET 3.5, it was relatively simple to create a markup extension for generic types - for example, this implementation on the MSDN forums[^] worked perfectly.

Unfortunately, in .NET 4.0, the IXamlTypeResolver service was updated to reject type names containing "`" - the separator between the type name and type argument count for generic types.

Mayur Shah's tip[^] avoids this by side-stepping the XAML type resolver. Whilst this works at runtime, it will fail at design-time. It also makes the type declaration unnecessarily long, since you can't use XML namespaces.

The Solution

The core of the solution involves using two services: IXamlNamespaceResolver and IXamlSchemaContextProvider. This is more complicated than the .NET 3.5 solution, but achieves the same result:

C#
var resolver = GetRequiredService<IXamlNamespaceResolver>(serviceProvider);
var schema = GetRequiredService<IXamlSchemaContextProvider>(serviceProvider);

var xamlNs = resolver.GetNamespace(namespaceName);
string genericTypeName = string.Format(CultureInfo.InvariantCulture, 
                "{0}`{1:D}", typeName, typeArguments.Length);

var xamlTypeName = new XamlTypeName(xamlNs, genericTypeName);
Type genericType = schema.SchemaContext.GetXamlType(xamlTypeName).UnderlyingType;

Type finalType = genericType.MakeGenericType(typeArguments);

Error-handling omitted for brevity.

Using the Code

The attached converter can be used in several ways:

XML
<!-- Inline: -->
<SomeTag Type="{nbs:GenericType ge:Queue, sys:String}"/>
<SomeTag Type="{nbs:GenericType ge:SortedList, sys:String, sys:Int32}"/>

<!-- Inline, using a static resource for the type arguments: -->
<SomeTag Type="{nbs:GenericType BaseTypeName=scg:Dictionary, 
TypeArguments={StaticResource types}}"/>

<!-- Inline, using a string for the type arguments: -->
<SomeTag Type="{nbs:GenericType BaseTypeName=scg:KeyValuePair, 
TypeArguments='sys:String, sys:Int32'}"/>

<!-- Expanded, using a static resource for the type arguments: -->
<SomeTag>
    <SomeTag.Type>
        <nbs:GenericType BaseTypeName="ge:SortedList" 
        TypeArguments="{StaticResource types}"/>
    </SomeTag.Type>
</SomeTag>

<!-- Expanded, specifying the type arguments as child elements: -->
<SomeTag>
    <SomeTag.Type>
        <nbs:GenericType BaseTypeName="ge:SortedDictionary">
            <x:Type TypeName="sys:String"/>

            <!-- Even nested generic types! -->
            <nbs:GenericType BaseTypeName="scg:List">
                <x:Type TypeName="sys:Int32"/>
            </nbs:GenericType>
        </nbs:GenericType>
    </SomeTag.Type>
</SomeTag>

Points of Interest

The attached class library is decorated with the XmlnsPrefix and XmlnsDefinition attributes. This makes it easier to use the namespace in a XAML document - instead of:

XML
xmlns:nbs="clr-namespace:XamlGenericTypeExtension;assembly=XamlGenericTypeExtension"

we can simply use:

XML
xmlns:nbs="urn:nbs-wpf-generic"

This has the added advantage that multiple namespaces can be mapped to the same XML namespace.

History

  • 6th February, 2015 - Initial version

Further Reading

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer CodeProject
United Kingdom United Kingdom
I started writing code when I was 8, with my trusty ZX Spectrum and a subscription to "Input" magazine. Spent many a happy hour in the school's computer labs with the BBC Micros and our two DOS PCs.

After a brief detour into the world of Maths, I found my way back into programming during my degree via free copies of Delphi and Visual C++ given away with computing magazines.

I went straight from my degree into my first programming job, at Trinet Ltd. Eleven years later, the company merged to become ArcomIT. Three years after that, our project manager left to set up Nevalee Business Solutions, and took me with him. Since then, we've taken on four more members of staff, and more work than you can shake a stick at. Smile | :)

Between writing custom code to integrate with Visma Business, developing web portals to streamline operations for a large multi-national customer, and maintaining RedAtlas, our general aviation airport management system, there's certainly never a dull day in the office!

Outside of work, I enjoy real ale and decent books, and when I get the chance I "tinkle the ivories" on my Technics organ.

Comments and Discussions

 
-- There are no messages in this forum --