XamlReader.Load(..)时出现异常

6

当我使用 (UIElement)XamlReader.Load(...) 时,出现了一个异常,提示如下:

'Cannot create unknown type 'TextBox'.' Line number '1' and line position '2'.

在以下的XAML代码中:
<TextBox Name="inputMyFirstString" BorderThickness="0" HorizontalAlignment="Stretch" Text="test"></TextBox>

What did i wrong?

3个回答

9

我知道这是一个老问题,但我认为仍然缺少“正确”的答案。 你可以通过在代码中添加所需的命名空间来避免更改XAML:

ParserContext context = new ParserContext();
context.XmlnsDictionary.Add("","http://schemas.microsoft.com/winfx/2006/xaml/presentation");
context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
//etc.

object content = XamlReader.Load(stream, context);

5

我认为这是由于缺少命名空间所致。请尝试添加命名空间

<TextBox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" ...

1
这样做是可行的,但在XAML中为每个控件添加命名空间并不是一个好主意。最好全局定义它。 - Winston Smith
1
@Winston Smith:我已经在我的控件中定义了命名空间,我可以在哪里全局定义命名空间? - elCapitano

0
在你的 XAML 中,为 Window 元素添加 xmlns 属性:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" ...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接