我在Windows Server 2008 Enterprise中使用SharePiont Server 2007 Enterprise,並使用發佈門戶模板。我正在開發使用VSTS 2008 + C#+ .Net 3.5。我想知道如何將WebPart添加到SharePoint網站的所有頁面?任何參考樣本?如何將WebPart添加到SharePoint網站中的所有頁面?
我想使用此WebPart在所有頁面上顯示一些常見信息(但信息可能會動態更改,這也是我選擇WebPart的原因)。
我在Windows Server 2008 Enterprise中使用SharePiont Server 2007 Enterprise,並使用發佈門戶模板。我正在開發使用VSTS 2008 + C#+ .Net 3.5。我想知道如何將WebPart添加到SharePoint網站的所有頁面?任何參考樣本?如何將WebPart添加到SharePoint網站中的所有頁面?
我想使用此WebPart在所有頁面上顯示一些常見信息(但信息可能會動態更改,這也是我選擇WebPart的原因)。
根據你的情況,有兩種方法可以做到這一點。
如果已經存在的網站,你需要遍歷的網站,加入網絡的一部分:
http://blogs.msdn.com/tconte/archive/2007/01/18/programmatically-adding-web-parts-to-a-page.aspx
如果不存在的站點,那麼你可以添加Web部件添加到網站模板:
這裏的西拉的第一個鏈接的代碼制定了多一點:
(注:此代碼沒有經過優化,例如,通過列表的Items集合循環是不是你通常應該做的事,但看到這可能是一次性的動作沒有任何問題)
private void AddCustomWebPartToAllPages()
{
using(SPSite site = new SPSite("http://sharepoint"))
{
GetWebsRecursively(site.OpenWeb());
}
}
private void GetWebsRecursively(SPWeb web)
{
//loop through all pages in the SPWeb's Pages library
foreach(var item in web.Lists["Pages"].Items)
{
SPFile f = item.File;
SPLimitedWebPartManager wpm = f.GetLimitedWebPartManager(PersonalizationScope.Shared);
//ADD YOUR WEBPART
YourCustomWebPart wp = new YourCustomWebPart();
wp.YourCustomWebPartProperty = propertyValue;
wpm.AddWebPart(wp, "ZONEID", 1);
f.Publish("Added Web Part");
f.Approve("Web Part addition approved");
}
// now do this recursively
foreach(var subWeb in web.Webs)
{
GetWebsRecursively(subWeb);
}
web.Dispose();
}
很酷,謝謝你! – George2 2009-12-07 13:06:34
我需要將WebPart添加到現有站點。我讀了第一篇文章的代碼。它提到了如何添加文檔庫Web部件,但是如何添加自定義開發的Web部件? – George2 2009-12-06 12:14:12
謝謝!問題回答了! – George2 2009-12-07 13:05:58