Search code examples
c#.netwpfnamespacesmarkup-extensions

How to properly remap my XAML namespace?


I have created a markup extension:

namespace Utils
{
    public class CoolExtension : MarkupExtension
    {
        private string key;

        public CoolExtension ()
        {
        }

        public CoolExtension(string key)
        {
            this.key = key;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return "!"+key+"!";
        }
    }
}

Next, I added in the AssemblyInfo the XmlnsDefinitionAttribute to remap the namespace Utils to Default-Namespace, so that I don´t need a namespace to use the markup extension:

[assembly: XmlnsDefinitionAttribute("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "Utils")]

Finally, in my window I used the extension:

<Button Content="{Cool test}" />

The XAML-Editor don´t underline anything to show an error and the XAML-Designer shows the output as expected (a button with "!test!" as content).

But it does not compile! In the error list I have the message that "Cool" wasn´t found in the namespace http://schemas.microsoft.com/

What I´m doing wrong (to get rid of the namespace for my extension)?


Solution

  • Unfortunately, WPF does not support this within the same assembly. The root cause that prevents the usage of the XmlnsDefinition in the same namespace is that, the XAML file must be parsed before the assembly is built in order to generate the code implied by the XAML to be included in the assembly.

    The XAML compiler produces code behind files (the files ending in, for example, .g.cs) and these file then become part of the assembly the XAML file is contained in.

    Since the assembly hasn't been built yet, the XAML compiler cannot load it to determine XmlnsDeclaration attributes have been specified.