1

我知道对于具有指定clr-namespace:assembly=标记的控件,XamlReader 只是在指定程序集中查找该类型。

但是默认命名空间中的默认 WPF 控件xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"呢?

我正在尝试获取 XElement 树中每个元素的类型,但我不知道在未指定程序集时如何找到它?

例如,以下所有示例都返回 null:

  • Type.GetType("Grid")
  • typeof(Control).Assembly.GetType("Grid")
  • Assembly.GetAssembly(typeof(Control)).GetType("Grid")

帮助?

4

1 回答 1

4

要复制 的行为XamlReader,您可以使用 aXamlSchemaContext来执行类型的查找。有关详细信息,请参阅MSDN 上的Default XAML Schema Context 和 WPF XAML Schema Context

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 资源。

于 2015-02-20T22:55:42.680 回答