2

我想加载一个Silverlight项目来读取每个XAML文件,方法是使用每个XAML类的反射Activator.CreateInstance来创建一个实例来读取其控件。如何动态加载XAML获取控件信息

C#代码:

string strPath = "SilverlightUI.dll"; 
StreamResourceInfo sri = Application.GetResourceStream(new Uri(strPath, UriKind.RelativeOrAbsolute)); 
AssemblyPart assemblyPart = new AssemblyPart(); 
Assembly assembly = assemblyPart.Load(sri.Stream); 
Type[] typeArray = assembly.GetExportedTypes(); 

foreach (Type type in typeArray) 
{ 
    object ctl = (object)Activator.CreateInstance(type); 
    // Following exception is occurring while creating an instance using above line of code 
    // Exception "Cannot find a Resource with the Name/Key ComboBoxStyle" 
} 

或许,反思是不是能够识别的Silverlight风格ComboBoxStyle。我怎么可能创建一个实例动态读取XAML文件中的每个控件?

回答

2

在与Google拼搏之后,我设法找到了解决我的问题所需的解决方案。

  1. 复制所有样式资源的Silverlight项目(拟装入)。
  2. 粘贴他们在主/来电的Silverlight项目或应用,这是使用反射代码来加载的App.xaml Silverlight的控制信息

执行这些步骤将消除XAML解析例外失踪风格

找不到与名称/密钥ComboBoxStyle

参考资源:XAML Parser cannot find resource within dynamically loaded XAP when creating form instance

-1

我能够使用XamlReader类加载自定义控件。
我正在使用包含控件的XAML的纯字符串,而不像您的反射想法。

//string xaml = "<...>"; 
var content = XamlReader.Load(xaml) as FrameworkElement; 
this.scrollViewer.Content = content; 

类型XamlReaderSystem.Windows.Markup

如果在您的情况下可以尝试从您的程序集中获取XAML资源并将它们读取到字符串中。然后使用提供的代码。在获得content变量后,您可以使用Silverlight API执行任何操作。
希望这会帮助你。