本文主要讲解如何在Spread for MVC的CommandBar上添加自定义按钮,如果之前使用过Spread for ASP.NET 产品,您可能已经清楚在CommandBar上添加自定义按钮并不是一项复杂的工作,只需重写 PreRender 方法,并在CommandBar上添加你需要的按钮即可,在 Spread for MVC 中也是同样的实现思路。文将在CommandBar上添加一个ImageButton按钮,并处理该按钮的客户端和服务端的单击事件。

首先,在Web页面中添加Spread MVC控件,添加控件之后可以在 Controller 中访问Spread控件,并处理PreRender和ButtonCommand事件,代码如下:

public ActionResult Index([FarPoint.Mvc.Spread.MvcSpread]FarPoint.Mvc.Spread.FpSpread FpSpread1)
{
    ViewBag.Message = "ComponentOne Spread Customized CommandBar";
    if (FpSpread1 != null)
    {
       FpSpread1.PreRender += new EventHandler(FpSpread1_PreRender);
       FpSpread1.ButtonCommand += new FarPoint.Web.Spread.SpreadCommandEventHandler(FpSpread1_ButtonCommand);
    }
    return View();
}

 

在Spread的PreRender事件中我们将处理Page的PreRenderComplete事件,代码如下:

void FpSpread1_PreRender(object sender, EventArgs e)
{
   FarPoint.Mvc.Spread.FpSpread fpspread1 = (FarPoint.Mvc.Spread.FpSpread)sender;
   System.Web.UI.Page page = fpspread1.Page;
   page.PreRenderComplete += new EventHandler(page_PreRenderComplete);
}

 

接下来,我们将在Spread的CommandBar中添加一个自定义的ImageButton控件,首先,我们需要检查指定的按钮是否已经在CommandBar上,代码如下:

void page_PreRenderComplete(object sender, EventArgs e)
{
    System.Web.UI.Page page = (System.Web.UI.Page)sender;
    FarPoint.Mvc.Spread.FpSpread spread = (FarPoint.Mvc.Spread.FpSpread)page.FindControl("FpSpread1");
    System.Web.UI.Control p = spread.FindControl("Print");
    if (p != null)
    {
       System.Web.UI.WebControls.TableCell tc = (System.Web.UI.WebControls.TableCell)p.Parent;
       System.Web.UI.WebControls.TableRow tr = (System.Web.UI.WebControls.TableRow)tc.Parent;
       System.Web.UI.WebControls.TableCell tableCell = new System.Web.UI.WebControls.TableCell();
       tr.Cells.Add(tableCell);
       System.Web.UI.WebControls.ImageButton btn = new System.Web.UI.WebControls.ImageButton();
       btn.ImageUrl = "~/Images/BELL.bmp";
       btn.Attributes.Add("OnClick", "onBellClick()");
       tableCell.Controls.Add(btn);
    }
}

以下代码是自定义按钮对应的客户端单击事件处理代码:

<script type ="text/javascript">
onBellClick = function ()
{
    alert("Image button is clicked!");
    var ss = FpSpread("FpSpread1");
    ss.CallBack("ImageButton");
}
</script>;

在onBellClick中调用CallBack之后,会触发Spread的ButtonCommand事件,然后我们可以通过 e.CommandName 来判断是否为 ImageButton,代码如下:

void FpSpread1_ButtonCommand(object sender, FarPoint.Web.Spread.SpreadCommandEventArgs e)
{
    if (e.CommandName == "ImageButton")
   {
      FarPoint.Mvc.Spread.FpSpread fpspread1 = (FarPoint.Mvc.Spread.FpSpread)sender;
      FarPoint.Web.Spread.ImageCellType img = new FarPoint.Web.Spread.ImageCellType();
      img.ImageUrl = "~/Images/Bell.bmp";
      fpspread1.ActiveSheetView.Cells[0, 0].CellType = img;
   }
}

在ImageButton调用中,我们将设置Spread的A1单元的CellType,以显示一幅图片,最终运行效果如下:

 

ImageButton

 

源码下载:VS2010 + Spread .NET 6

CustomizingCommandBar.zip (493.34 kb)