我知道对于具有指定 clr-namespace: 和 assembly= 标记的控件,XamlReader 只是在指定的程序集中查找该类型。
但是默认命名空间 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 中的默认 WPF 控件呢?
我正在尝试获取 XElement 树中每个元素的 Type,但在没有指定程序集的情况下我不知道如何找到它?
例如,以下所有示例都返回 null:
Type.GetType("Grid")typeof(Control).Assembly.GetType("Grid")Assembly.GetAssembly(typeof(Control)).GetType("Grid")
帮忙吗?
请您参考如下方法:
要复制 XamlReader 的行为,您可以使用 XamlSchemaContext 来执行类型查找。详见Default XAML Schema Context and WPF XAML Schema Context在 MSDN 上。
GetXamlType方法允许您传递 Xaml 命名空间和类型名称:
var context = new XamlSchemaContext();
var xtype = context.GetXamlType(new XamlTypeName("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "Grid"));
var gridType = xtype.UnderlyingType;
// gridType == typeof(System.Windows.Controls.Grid)
请注意,此技术在存在命名空间时也适用,它允许您使用单一的统一机制来解析 Xaml 资源。
