Weird Behaviour of XamlReader.Load() function

227 Views Asked by At

I want to create wpf controls using xml literals and xamlreader.load(). But I'm stuck trying to load xml literals containing property element notation because it keeps throwing the XamlParseException "Cannot set unknown member".

Details:

This works

Dim xmlObj = <TextBlock
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

                 <TextBlock.Text>Hello World</TextBlock.Text>

             </TextBlock>

Dim txtB As TextBlock = Markup.XamlReader.Load(xmlObj.CreateReader())

The textblock is created, and the text property is properly set with no exceptions.
But the code below doesn't work

Dim xmlPropFunc = Function() (<TextBlock.Text>Hello World</TextBlock.Text>)
Dim xmlObj = <TextBlock
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

                  <%= xmlPropFunc() %>

             </TextBlock>

Dim txtB As TextBlock = Markup.XamlReader.Load(xmlObj.CreateReader())

The code fragment above throws a XamlParseException, saying "Cannot set unknown member TextBlock.Text"

I am relatively new to using xml, and wpf/xaml, so I don't really know what's going on here. I'm using VB.Net with visual studio 2015 community edition.
Thanks in advance for your assistance.

1

There are 1 best solutions below

3
On

I'm not surprised including xml functions causes problems.

Xamlreader.load is trying to do a direct conversion from what you give it. Make sure that's plain xml.

Basically.

If you take the string and paste it into a wpf window.

If you get no errors and the window loads ok then you have a chance of success.

If there are errors or it doesn't work when you paste in then your xamlreader.load is very unlikely to work.

Either use standard xml substitition to replace a node or string substitution before you convert to xml.

There are working examples of both in the samples linked here:

https://social.technet.microsoft.com/wiki/contents/articles/28797.wpf-dynamic-xaml.aspx