Silverlight中的反射与.NET FRAMEWORK中的略有不同。以下分三种情况描述:
1:动态创建当前执行的程序集中的类实例。
2:动态创建XAP包中其它SILVERLIGHT程序集中的类实例。
3:动态下载并创建网站上其它SILVERLIGHT程序集中的类实例。
1:动态创建当前执行的程序集中的类实例
示例代码如下,其中ChildWindowMsg是你自己创建的类。
- Assembly assem = Assembly.GetExecutingAssembly();
- ChildWindowMsg cw = assem.CreateInstance("YiPin.QuestionsDbSL.ChildWindowMsg") as ChildWindowMsg;
2:动态创建XAP包中其它SILVERLIGHT程序集中的类实例
- Assembly assem = Assembly.GetExecutingAssembly();
- ChildWindowMsg cw = Assembly.Load("YiPin.QuestionsDbSL").CreateInstance("YiPin.QuestionsDbSL.ChildWindowMsg") as ChildWindowMsg;
3:动态下载并创建网站上其它SILVERLIGHT程序集中的类实例
- For example we can write a usercontrol to download the assembly:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Documents;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Animation;
- using System.Windows.Shapes;
- using System.Reflection;
- namespace SilverlightApplication15
- {
- public partial class DownloadUserControl : UserControl
- {
- public string Source { get; set; }
- public DownloadUserControl()
- {
- InitializeComponent();
- this.Loaded += new RoutedEventHandler(DownloadUserControl_Loaded);
- }
- void DownloadUserControl_Loaded(object sender, RoutedEventArgs e)
- {
- WebClient client = new WebClient();
- client.OpenReadCompleted += new OpenReadCompletedEventHandler(OnAssemblyOpened);
- client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
- client.OpenReadAsync(new Uri(Source));
- }
- void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
- {
- this.txtProgress.Text = e.ProgressPercentage + "%";
- }
- void OnAssemblyOpened(object sender, OpenReadCompletedEventArgs e)
- {
- AssemblyPart assemblyPart = new AssemblyPart();
- Assembly assembly = assemblyPart.Load(e.Result);
- Control largecontrol = assembly.CreateInstance("LargeCustomControl.LargeControl") as Control;
- if (largecontrol != null) {
- this.txtProgress.Visibility = Visibility.Collapsed;
- this.LayoutRoot.Children.Add(largecontrol);
- }
- }
- }
- }
- <UserControl x:Class="SilverlightApplication15.DownloadUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- Width="400" Height="300">
- <Grid x:Name="LayoutRoot" Background="White">
- <TextBlock x:Name="txtProgress"></TextBlock>
- </Grid>
- </UserControl>
- To use it in Page.xaml:
- <c:DownloadUserControl Source="http://localhost/LargeCustomControl.dll"></c:DownloadUserControl>
- You just have to privde the uri of the dll of your large custom control.