Prism または MEF フレームワークを使用して xap モジュールを動的にロードできることを知っています。ただし、これらのフレームワークは使用したくありません。代わりに、xap ファイルを手動でロードします。そこで、次のクラスを作成しました(インターネットから適応):
public class XapLoader
{
public event XapLoadedEventHandler Completed;
private string _xapName;
public XapLoader(string xapName)
{
if (string.IsNullOrWhiteSpace(xapName))
throw new ArgumentException("Invalid module name!");
else
_xapName = xapName;
}
public void Begin()
{
Uri uri = new Uri(_xapName, UriKind.Relative);
if (uri != null)
{
WebClient wc = new WebClient();
wc.OpenReadCompleted += onXapLoadingResponse;
wc.OpenReadAsync(uri);
}
}
private void onXapLoadingResponse(object sender, OpenReadCompletedEventArgs e)
{
if ((e.Error == null) && (e.Cancelled == false))
initXap(e.Result);
if (Completed != null)
{
XapLoadedEventArgs args = new XapLoadedEventArgs();
args.Error = e.Error;
args.Cancelled = e.Cancelled;
Completed(this, args);
}
}
private void initXap(Stream stream)
{
string appManifest = new StreamReader(Application.GetResourceStream(
new StreamResourceInfo(stream, null), new Uri("AppManifest.xaml",
UriKind.Relative)).Stream).ReadToEnd();
XElement deploy = XDocument.Parse(appManifest).Root;
List<XElement> parts = (from assemblyParts in deploy.Elements().Elements()
select assemblyParts).ToList();
foreach (XElement xe in parts)
{
string source = xe.Attribute("Source").Value;
AssemblyPart asmPart = new AssemblyPart();
StreamResourceInfo streamInfo = Application.GetResourceStream(
new StreamResourceInfo(stream, "application/binary"),
new Uri(source, UriKind.Relative));
asmPart.Load(streamInfo.Stream);
}
}
}
public delegate void XapLoadedEventHandler(object sender, XapLoadedEventArgs e);
public class XapLoadedEventArgs : EventArgs
{
public Exception Error { get; set; }
public bool Cancelled { get; set; }
}
上記のコードは問題なく動作します。次の方法で任意の xap をロードできます。
XapLoader xapLoader = new XapLoader("Sales.xap");
xapLoader.Completed += new XapLoadedEventHandler(xapLoader_Completed);
xapLoader.Begin();
さて、Sales.xap プロジェクトに InvoiceView という UserControl があるので、このクラスをインスタンス化したいと思います。現在のプロジェクト (Main.xap) では、Sales.xap プロジェクトへの参照を追加しましたが、手動で読み込むため、"Copy Local = False" を設定しました。しかし、実行すると、次のコードは TypeLoadException をスローします。
Sales.InvoiceView view = new Sales.InvoiceView();
コードが InvoiceView クラスを見つけられないようです。しかし、XapLoader の initXap() メソッドが正常に実行されることを確認しました。では、なぜコードは InvoiceView クラスを見つけられないのでしょうか? 誰かがこの問題で私を助けることができますか?