如何动态加载XAML以获取控件信息
我正在尝试加载一个 Silverlight 项目来读取每个 XAML
文件,方法是使用每个 XAML
类的反射 Activator.CreateInstance
创建一个实例读取其控件。
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 文件中的每个控件?
I am trying to load a Silverlight project to read every XAML
file by creating an instance using reflection, Activator.CreateInstance
, of every XAML
class for reading its controls.
C# Code:
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"
}
Perhaps, reflection is not able to recognize Silverlight style ComboBoxStyle
. How can i possibly create an instance to read every control in the XAML file dynamically?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
经过与谷歌的斗争后,我终于找到了解决问题所需的方法。
App.xaml
中,该项目或应用程序使用反射代码加载 Silverlight 控件信息遵循这些步骤将消除缺少样式的XAML解析异常。
参考的资源: 创建表单实例时,XAML 解析器无法在动态加载的 XAP 中找到资源
I have managed to find the required solution to my problem after struggling with the Google.
App.xaml
of the Master/Caller Silverlight project or application, which is using the reflection code to load the Silverlight Controls informationFollowing these steps will eliminate the XAML Parse Exception of missing Style.
Reference: XAML Parser cannot find resource within dynamically loaded XAP when creating form instance
我能够使用
XamlReader
类加载自定义控件。我使用的是包含控件的 XAML 的纯字符串,与您的反射想法不同。
XamlReader
类型位于System.Windows.Markup
中。如果您的情况可能,您可以尝试从程序集中获取 XAML 资源并将它们读取为字符串。然后使用提供的代码。获得
content
变量后,您可以使用 Silverlight API 对控件执行任何操作。希望这会对您有所帮助。
I was able to load custom controls using the
XamlReader
class.I am using plain string that contains the XAML of the control not like your reflection idea.
The type
XamlReader
is inSystem.Windows.Markup
.If it is possible in your case you can try to get XAML resources from your assembly and read them to string. Then use the provided code. After you have the
content
variable you can do anything using the Silverlight API to the control.Hope this will help you.