wpfuielementxamlreader

WPF - cannot parse TextBlock element from string


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?


Solution

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

    addElementToView("<TextBox Text=\"hello\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"/>");