C# 加载XamlReader.Load(..)时发生异常
我在(UIElement)XamlReader.Load(…)期间遇到一个异常,它表示C# 加载XamlReader.Load(..)时发生异常,c#,xaml,C#,Xaml,我在(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&
'Cannot create unknown type 'TextBox'.' Line number '1' and line position '2'.
在以下xaml上:
<TextBox Name="inputMyFirstString" BorderThickness="0" HorizontalAlignment="Stretch" Text="test"></TextBox>
我做错了什么?我想,这是因为。试一试
将xmlns属性添加到XAML中的窗口元素:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" ...
我知道这是一个老问题,但我认为“正确”的答案仍然缺失。
通过在代码中添加所需的名称空间,可以避免更改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);
这是可行的,但是将名称空间添加到XAML中的每个控件不是一个好主意。最好全局定义它。@Winston Smith:我已经在控件中定义了名称空间,并将文本框添加到该名称空间中。我还可以在哪里全局定义名称空间?
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);