public class WebPartWrapper : System.Web.UI.WebControls.WebParts.WebPart {
protected override void CreateChildControls() {
Panel pnl = new Panel();
this.Controls.Add(pnl);
var factory = new WebPartFactory()
WebPart dynamicPart = factory.CreateWebPart("RSSViewer", this.Guid);
pnl.Controls.Add(dynamicPart);
}
}
public class WebPartFactory {
public WebPart CreateWebpart(string webpartName, Guid parentWebPartGuid)
{
var config = ConfigurationFactory.LoadConfiguration(webpartName);
Assembly webPartAssembly = Assembly.Load(config.Assembly);
Type webPartType = webPartAssembly.GetType(config.Class);
object actualWebPart = Activator.CreateInstance(webPartType);
foreach (var item in config.Properties)
{
PropertyInfo webPartProperty = webPartType.GetProperty(item.Name);
object webPartPropertyValue = Convert.ChangeType(itemValue, Type.GetType(item.Type));
if (!String.IsNullOrEmpty(item.Value))
webPartProperty.SetValue(actualWebPart, webPartPropertyValue, null);
}
RunMethod("set_StorageKeyInternal", actualWebPart, new object[] { parentWebPartGuid });
return actualWebPart as WebPart;
}
private void RunMethod(string methodName, object objectInstance, object[] methodParameters)
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public |
BindingFlags.NonPublic;
Type t = objectInstance.GetType();
MethodInfo m = GetMethod(t, methodName, flags);
if (m != null)
{
m.Invoke(objectInstance, methodParameters);
}
}
private MethodInfo GetMethod(Type instanceType, string methodName, BindingFlags flags)
{
MethodInfo m = instanceType.GetMethod(methodName, flags);
if (m != null)
{
return m;
}
if (instanceType.GetType() == typeof(object) || instanceType.BaseType == null)
{
return null;
}
return GetMethod(instanceType.BaseType, methodName, flags);
}
}
このコードには説明が必要です... コンパイルされない場合はすみません。元のコードのかなりの部分を削除する必要がありました。これは非常に実装固有のものでした。「config」クラスも示していません。これは単なる Web パーツ構成用のコンテナーであり、一連のプロパティです。より詳細に議論したい 2 つの問題があります。
parentWebPartGuid - これは、ホスティング Web パーツの Guid (UniqueId?) です。何らかの理由で、リフレクションを使用して "StorageKeyInternal" をこの値に設定する必要があります (これはプライベート プロパティです)。設定しなくても済む可能性がありますが、少なくとも大部分の Web パーツでは設定する必要がありました。
config.Properties - これは設定値です (カスタム .xml ファイルで設定しますが、どこからでも自由に取得できます)。これは少し似ているかもしれません..
私たちのフレームワークでは、動的プロパティ値などもサポートしていますが、それはまた別の機会に... これがすべて意味をなして、誰かを助けることができることを願っています.