0

I'm new in WPF

I need to get string param, create an UIElement and attach it to the view. Parsing the element from the string is failed, I don't know why.

Here is the code:

public void addElementToView(string str)
{
      object obj = XamlReader.Load(new XmlTextReader(new StringReader(str)));
      UIElement elem = (UIElement)obj;
      SpecialContent.Children.Add(elem);
}

call addElementToView("<TextBox Text=\"hello\"/>") fails with the following exception:

A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll

Additional information: 'Cannot create unknown type 'TextBlock'.' Line number '1' and line position '2'.

It failes in this row:

object obj = XamlReader.Load(new XmlTextReader(new StringReader(str)));

Any idea?

Community
  • 1
  • 1
user5260143
  • 1,048
  • 2
  • 12
  • 36

1 Answers1

0

You should have the necessery namespace in xml. like following,

addElementToView("<TextBox Text=\"hello\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"/>");
Mertus
  • 1,145
  • 11
  • 17