下面的示例代码演示如何从主机服务器按需检索程序集,然后将其加载到当前应用程序域中。
此示例使用 WebClient 类启动程序集的异步下载以响应用户鼠标单击。当下载完成后,将使用 AssemblyPart 类来加载此程序集。
此示例假定您已在您的应用程序项目中添加了对程序集的引用。该程序集的"复制本地"值还必须为"False",这样,它将不会部署在应用程序包中。有关更多信息,请参见应用程序结构。
示例
XAML
复制代码
Page from Host Application
Click Here to Display a UI from the Library Assembly
Visual Basic
复制代码
Imports SilverlightLibraryPartial Public Class HomePage
Inherits UserControl
Public Sub New()
InitializeComponent()
End Sub
Private Sub TextBlock_MouseLeftButtonUp(ByVal sender As Object, _
ByVal e As MouseButtonEventArgs)
' Download an "on-demand" assembly.
Dim wc As New WebClient()
AddHandler wc.OpenReadCompleted, AddressOf wc_OpenReadCompleted
wc.OpenReadAsync(New Uri("SilverlightLibrary.dll", UriKind.Relative))
End Sub
Private Sub wc_OpenReadCompleted(ByVal sender As Object, _
ByVal e As OpenReadCompletedEventArgs)
If (e.[Error] Is Nothing) AndAlso (e.Cancelled = False) Then
' Convert the downloaded stream into an assembly that is
' loaded into current AppDomain.
Dim assemblyPart As New AssemblyPart()
assemblyPart.Load(e.Result)
DisplayPageFromLibraryAssembly()
End If
End Sub
Private Sub DisplayPageFromLibraryAssembly()
' Create an instance of the Page class in the library assembly.
Dim page As New Page()
' Display the new Page.
Me.stackPanel.Children.Add(page)
End Sub
End Class
C#
复制代码
using System; // Uriusing System.Net; // WebClient,OpenReadCompletedEventHandler
using System.Windows; // AssemblyPart
using System.Windows.Controls; // UserControl
using System.Windows.Input; // MouseButtonEventArgs
using SilverlightLibrary; // Page
namespace SilverlightApplication
{
public partial class HomePage : UserControl
{
public HomePage()
{
InitializeComponent();
}
private void TextBlock_MouseLeftButtonUp(
object sender, MouseButtonEventArgs e)
{
// Download an "on-demand" assembly.
WebClient wc = new WebClient();
wc.OpenReadCompleted +=
new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(
new Uri("SilverlightLibrary.dll", UriKind.Relative));
}
private void wc_OpenReadCompleted(
object sender, OpenReadCompletedEventArgs e)
{
if ((e.Error == null) && (e.Cancelled == false))
{
// Convert the downloaded stream into an assembly that is
// loaded into current AppDomain.
AssemblyPart assemblyPart = new AssemblyPart();
assemblyPart.Load(e.Result);
DisplayPageFromLibraryAssembly();
}
}
private void DisplayPageFromLibraryAssembly() {
// Create an instance of the Page class in the library assembly.
Page page = new Page();
// Display the new Page.
this.stackPanel.Children.Add(page);
}
}
}
若要查看该示例的运行版本,请单击下面的链接。
运行此示例
请参见
参考
WebClient
AssemblyPart
其他资源
应用程序结构