[译者改后代码下载]
原文发布日期:2007.03.01
作者:Abdul Sami
翻译:webabcd
介绍
如果说WebParts是web中一个非酷的效果的话,我想没有人会怀疑。WebParts为我们提供了对页中的对象进行拖拽的功能,它也可以在runtime的时候改变对象的标题、边框样式等。在WebParts出现之前,要实现这个功能是一项令人非常头痛的工作,因为我们必须写大量的JavaScrip,还要把页中每个对象的状态保存到数据库中。
WebParts有两个基本的东东
·WebPartManager
·WebPart Zones
WebPartManager用来管理所有的webparts。如果你想在你的web站点中使用webparts就必须要使用WebPartManager。它的作用是提供你在页中进行拖拽的JavaScript代码
WebPart Zones
WebPart Zones中有4个zone
·WebPartZone
·EditorZone
·CatalogZone
·ConnectionZone
WebPartZone
WebPartZone是webparts里最基本的单位。通过在WebPartZone里放置不同的内容,我们就能够允许用户在页上对其进行拖拽。你可以在你的页上增加一个DropDownList以实现使用不同zone的功能,该DropDownList的选项如下
·Browse
·Design
·Edit
·Catalog
·Connect
在DropDownList的SelectedIndexChanged事件里粘贴如下代码(这里假设DropDownList的id是“cmbOptions”,WebPartManager的id是“WebPartManager1”)
{
WebPartManager1.DisplayMode = WebPartManager.DesignDisplayMode;
}
else if (cmbOptions.SelectedValue == "Browse")
{
WebPartManager1.DisplayMode = WebPartManager.BrowseDisplayMode;
}
else if (cmbOptions.SelectedValue == "Catalog")
{
WebPartManager1.DisplayMode = WebPartManager.CatalogDisplayMode;
}
else if (cmbOptions.SelectedValue == "Edit")
{
WebPartManager1.DisplayMode = WebPartManager.EditDisplayMode;
}
else if (cmbOptions.SelectedValue == "Connect")
{
WebPartManager1.DisplayMode = WebPartManager.ConnectDisplayMode;
}
Browse mode是webparts的默认模式。在Browse mode中虽然我们不能拖拽webpart,但是可以在webpart上看到两个选项,最小化和关闭。最小化一个webpart会显示它的最小化状态,如果选择关闭的话我们就只能在Catalog mode下重新恢复它,稍后我们会讨论它。这里有一个Browse mode下简单的webpart的图例
在Design mode中我们就可以在两个webpart对象间进行拖拽了。我这里有两个webpart,分别被命名为“Links”和“Search”。下图示例了把“Links”拖拽到“Search”的情况
Edit Mode允许你在runtime中编辑webpart。编辑webpart是一个比较深层次的应用,它分为4个类型:Appearance、Behavio、Property和Layout。我们首先来看看如何使用Appearance和LayoutEditorPart
Appearance和LayoutEditorPart
首先在web form上放置一个EditorZone。然后在EditorZone里放置一个AppearanceEditorPart和LayoutEditorPart。运行这个程序,从DropDownList中选择编辑模式。在可用的webpart上单击菜单的编辑按钮。
PropertyGridEditorPart
通过使用属性编辑器我们可以改变webpart中对象的属性。在我们的例子中将示例如何改变对象的CssClass属性。我们将用与解释AppearanceEditorPart和LayoutEditorPart相同的方法来说明它
在webform上放置一个EditorZone。然后在EditorZone里放置一个PropertyGridEditorPart。为了使用EditorZone我们需要在你的项目里新增一个用户控件。在这个用户控件里放置一个TextBox,然后再把这个用户控件放到web form的webpart里。该用户控件的后置代码如下
[WebBrowsable(), Personalizable(true)]
public string CssClass
{
get { return _cssClass; }
set { TextBox1.CssClass= value; }
}
protected void Page_Load(Object sender, EventArgs e)
{
TextBox1.CssClass = CssClass;
}
·WebBrowsable - 允许webpart在编辑模式中显示用户定义的属性
·Personalizable - 允许属性是可编辑的
现在运行这个页。如果我们设置了WebPartManager为编辑模式的话,就将会看到webpart的菜单选项中出现了编辑按钮。截屏如下
Catalog mode
Catalog mode给我们提供了在运行时添加和移除webpart的选项。例如,如果我们有一些模块,如天气模块、新闻模块、购物模块和占卜模块等等。如果想在运行时给用户提供显示和隐藏这些模块的选项,我们就可以使用Catalog mode来完成这项任务。
CatalogZone
CatalogZone分为3个类型,分别是PageCatalogPart、DeclarativeCatalogPart和ImportCatalogPart。在webform上增加一个CatalogZone,然后在CatalogZone内添加之前提到的3个类型。当webpart被关闭后我们可以用PageCatalog来帮我们来显示webpart,截屏如下: