使用接口简单实现Silverlight项目和UserControl的多级切换

Silverligth文件比较大时,考虑到下载速度和时间的问题,可能需要对程序进行分割,分割成各个子项目组件,并在运行时动态下载需要的组件,下载后在主载体页面中进行组件切换,这样就能节约第一次下载的文件大小,并延长了下载时间,可以大大的提高用户体验。

      1.首先来看看事例的组成:

MainContent是主载体,MainContent.Web是。。。这个不用说了吧

SLBookDemoApp 和 SLBookDemoApp1 是两个测试的子项目

SLInterfaces 是接口类项目

 

      2.接口代码,主项目的MainPage和子项目的Switcher都继承该接口


public interface ISwitcher
{
    
/// <summary>
    
/// 切换组件
    
/// </summary>
    void SwitchComponent(string componentName);

    
/// <summary>
    
/// 切换当前组件下的页面
    
/// </summary>
    
/// <param name="viewName"></param>
    void SwitchView(string viewName);
}

 

      3.实现切换,在UserControl中改变Content值

public void SwitchView(UserControl view)
{
     
this.Content = view;
}

 

      4.动态下载部分,这里参考了这位大哥的文章,主要的思路就是使用WebClient动态下载xap文件,并在客户端反射载入指定的UserControl


private void btn_Click(object sender, RoutedEventArgs e)
{
    WebClient client 
= new WebClient();
    client.OpenReadCompleted 
+= new OpenReadCompletedEventHandler(client_OpenReadCompleted);
    
//打开打包的xap文件
    client.OpenReadAsync(new Uri("DynamicXap.xap", UriKind.Relative));
}

void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    
//解包,读取AppManifest.xaml文件信息
    string appManifest = new StreamReader(Application.GetResourceStream(
                 
new StreamResourceInfo(e.Result, null), 
                 
new Uri("AppManifest.xaml", UriKind.Relative)).Stream).ReadToEnd();

    
//------------解析AppManifest.xaml信息内容
    XElement deploymentRoot = XDocument.Parse(appManifest).Root;
    List
<XElement> deploymentParts = (from assemblyParts in deploymentRoot.Elements().Elements()
      select assemblyParts).ToList();

    Assembly asm 
= null;
    
foreach (XElement xElement in deploymentParts)
    {
        
string source = xElement.Attribute("Source").Value;
        AssemblyPart asmPart 
= new AssemblyPart();
        StreamResourceInfo streamInfo 
= Application.GetResourceStream(
                                
new StreamResourceInfo(e.Result, "application/binary"), 
                                
new Uri(source, UriKind.Relative));
        
if (source == "DynamicXap.dll")
        {
            asm 
= asmPart.Load(streamInfo.Stream);
        }
        
else
        {
            asmPart.Load(streamInfo.Stream);
        }
    }
    
//======================
    divshow.Children.Clear();
    divshow.DataContext 
= DataOP.getUsers(txtInput.Text);
    
//转换此assembly为UIElement
    UIElement myData = asm.CreateInstance("DynamicXap.Page"as UIElement;
    divshow.Children.Add(myData);
    divshow.UpdateLayout();
}
共有0个回答