0

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 Answers1

0

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

Andy
  • 11,864
  • 2
  • 17
  • 20
  • Thanks @Andy, but i'll need to read them up. I'll get back to you ASAP – Aniekan Daniel Jul 30 '20 at 09:18
  • But I noticed generally that dynamically generating property element syntax does not work except if the property element syntax is already in the xml. I'll need to specify the property element syntax explicitly, instead of producing it during run time. Is there any way around it? Am I missing a namespace? or is it a microsoft bug? – Aniekan Daniel Jul 30 '20 at 10:02
  • You need to add namespaces in the xaml itself. And. As I tried to explain above. If the string you get doesn't work when you paste it into a wpf window then it's very unlikely to work when you xamlreader.load. You should be creating a string that looks exactly like xaml. – Andy Jul 30 '20 at 10:25