Why does XamlReader throw when I use a ParserContext?

2.9k Views Asked by At

This works:

XamlReader.Parse("<Pig xmlns=\"clr-namespace:Farm;assembly=Farm\"/>");

This throws The tag 'Pig' does not exist in XML namespace 'clr-namespace:Farm;assembly=Farm':

var context = new ParserContext();
context.XmlnsDictionary.Add("", "clr-namespace:Farm;assembly=Farm");
XamlReader.Parse("<Pig/>", context);

Why?

Farm is the calling application.

1

There are 1 best solutions below

1
On BEST ANSWER

What you have will work in .NET 4.0, but unfortunately not in .NET 3.5. Try using XamlTypeMapper instead:

var context = new ParserContext();
context.XamlTypeMapper = new XamlTypeMapper(new string[] { });
context.XamlTypeMapper.AddMappingProcessingInstruction("", "Farm", "Farm");
XamlReader.Parse("<Pig/>", context);

If you wanted to use a namespace prefix, you could declare a clr namespace to xml namespace mapping with the XamlTypeMapper and then declare a namespace prefix for the xml namespace.

var context = new ParserContext();
context.XamlTypeMapper = new XamlTypeMapper(new string[] { });
context.XamlTypeMapper.AddMappingProcessingInstruction("Foo", "Farm", "Farm");
context.XmlnsDictionary.Add("a", "Foo");
XamlReader.Parse("<a:Pig/>", context);