Monday, December 31, 2007

ASP.NET 2.0 GridView 範例集

ASP.NET 2.0 GridView 範例集


文/黃忠成


這篇文章從何來?



在寫ASP.NET AJAX/Silverlight書之前,我曾經動過念頭撰寫一本ASP.NET 2.0聖經類型的書籍,也付諸執行了一段時間,完成了近500頁的書稿(500頁,僅是此書的3章....,全書規劃有15章),但由於工作上的關係,我終究沒能在ASP.NET 3.5推出前完成這一本書,只是將書中的ASP.NET/Silverlight抽出成為另一本書,但東西寫都寫好了,不將其公諸於世,總覺得對不起她們(我一直認為,文章在其完成時,即擁有作者所賦與的生命),雖然我可以將其收錄在未來可能撰寫的ASP.NET 3.5新書中,但由於近一年內的新書計劃中並沒有排定此書,遂決定將其中較實用的技巧抽出,貼在BLOG上面,與各位讀者分享,也算是送給各位長期支持我的讀者們,一份意外的聖誕禮物吧 ^_^。


PS:文章未經潤飾,不通順之處還請見諒。



漸層光棒



不喜歡GridView控件單調的Header區、單調的選取光棒嗎?這裡有個小技巧可以讓你的GridView控件看起來與眾不同,請先準備兩張圖形。

圖4-8-50(4-71.tif)


這種漸層圖形可以用Photoshop或PhotoImpact輕易做出來,接著將這兩個圖形檔加到專案的Images目錄中,左邊取名為titlebar.gif、右邊取名為gridselback.gif,然後開啟一個新網頁,組態SqlDataSource控件連結到任一資料表,再加入GridView控件繫結至此SqlDataSource控件,接著將Enable Selection打勾,切換至網頁Source頁面,加入CSS的程式碼。

程式4-8-10

<%@
Page
Language="C#"
AutoEventWireup="true"
CodeFile="GrandientSelGrid.aspx.cs"
Inherits="GrandientSelGrid"
%>

<!DOCTYPE
html
PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<style
type="text/css">

.grid_sel_back

{


background-image:url(Images/gridselback.gif);


background-repeat:repeat-x

}

.title_bar

{

background-image:url(Images/titlebar.gif);

background-repeat:repeat-x

}

</style>

完成後切回設計頁面,設定GridView控件的SelectedRowStyle及HeaderStyle屬性。

圖4-8-51(4-72.tif)


完成後執行網頁,你會見到很不一樣的GridView。

圖4-8-52(4-73.tif)



2 Footer or 2 Header



前面曾提及,GridView控件並沒有限制我們只能在裡面加入一個Footer,因此我們可以透過程式4-8-11的方式,添加另一個Footer至GridView控件中。

程式4-8-11

protected
void GridView1_PreRender(object sender, EventArgs e)

{


//if no-data in datasource,GridView will not create ChildTable.


if (GridView1.Controls.Count > 0 && GridView1.Controls[0].Controls.Count > 1)

{


GridViewRow row2 = new
GridViewRow(-1, -1,

DataControlRowType.Footer, DataControlRowState.Normal);


TableCell cell = new
TableCell();

cell.Text = "Footer 2";

cell.Attributes["colspan"] = GridView1.Columns.Count.ToString(); //merge columns

row2.Controls.Add(cell);

GridView1.Controls[0].Controls.AddAt(GridView1.Controls[0].Controls.Count - 1, row2);

}

}

相同的,同樣的方法也可以用於添加另一個Header至GridView控件中,這個範例看起來無用,但是卻給了無限的想像空間,這是實現GridView Insert及Collapsed GridView功能的基礎。


Group Header



想合併Header中的兩個欄位為一個嗎?很簡單!只要在RowCreated事件中將欲被合併的欄位移除,將另一欄位的colspan設為2即可。

程式4-8-12

protected
void GridView1_RowCreated(object sender, GridViewRowEventArgs e)

{


if (e.Row.RowType == DataControlRowType.Header)

{

e.Row.Cells.RemoveAt(3);

e.Row.Cells[2].Attributes["colspan"] = "2";

e.Row.Cells[2].Text = "Contact Information";

}

}

圖4-8-53為執行畫面。

圖4-8-53(4-74.tif)


我想,應該不需要我再解釋2這個數字從何而來了吧。 ^_^


Group Row


想將同值的欄位合成一個嗎?4-8-13的程式碼可以幫你達成。

程式4-8-13

private
void PrepareGroup()

{


int lastSupID = -1;


GridViewRow currentRow = null;


List<GridViewRow> tempModifyRows = new
List<GridViewRow>();


foreach (GridViewRow row in GridView1.Rows)

{


if (row.RowType == DataControlRowType.DataRow)

{


if (currentRow == null)

{

currentRow = row;


int.TryParse(row.Cells[2].Text, out lastSupID);


continue;

}



int currSupID = -1;


if (int.TryParse(row.Cells[2].Text, out currSupID))

{


if (lastSupID != currSupID)

{

currentRow.Cells[2].Attributes["rowspan"] = (tempModifyRows.Count+1).ToString();

currentRow.Cells[2].Attributes["valign"] = "center";


foreach (GridViewRow row2 in tempModifyRows)

row2.Cells.RemoveAt(2);

lastSupID = currSupID;

tempModifyRows.Clear();

currentRow = row;

lastSupID = currSupID;

}


else

tempModifyRows.Add(row);

}

}

}



if (tempModifyRows.Count > 0)

{

currentRow.Cells[2].Attributes["rowspan"] = (tempModifyRows.Count + 1).ToString();

currentRow.Cells[2].Attributes["valign"] = "center";


foreach (GridViewRow row2 in tempModifyRows)

row2.Cells.RemoveAt(2);

}

}


protected
void GridView1_PreRender(object sender, EventArgs e)

{

PrepareGroup();

}

這段程式碼應用了先前所提過的GridViewRow控件及TableCell的使用方式,圖4-8-54為執行結果。

圖4-8-54




Master-Detail GridView



Master-Detail,也就是主明細表的顯示,是資料庫應用常見的功能,運用DataSource及GridView控件可以輕易做到這點,請建立一個網頁,加入兩個GridView控件,一名為GridView1,用於顯示主表,二名為GridView2,用於顯示明細表,接著加入兩個SqlDataSource控件,一個連結至Northwind資料庫的Orders資料表,另一個連結至Order Details資料表,於連結至Order Details資料表的SqlDataSource中添加WHERE條件來比對OrderID欄位,值來源設成GridView1的SelectedValue屬性。

圖4-8-61


接下來請將GridView1的DataSoruce設為Orders的SqlDataSource,GridView2的DataSource設為Order Details的SqlDataSource,最後將GridView1的Enable Selection打勾即可完成Master-Detail的範例。

圖4-8-62


那這是如何辦到的呢?當使用者點選GridView1上某筆資料的Select連結時,GridView1的SelectedValue屬性便會設成該筆資料的DataKeyName屬性所指定的欄位值,而連結至Order Details的SqlDataSource又以該屬性做為比對OrderID欄位時的值來源,結果便成了,使用者點選了Select連結,PostBack發生,GridView2向連結至Order Details的SqlDataSource索取資料,該SqlDataSource以GridView1.SelectedValue做為比對OrderID欄位的值,執行選取資料的SQL指令後,該結果集便是GridView1所選取那筆資料的明細了。


Master-Detail GridView Part 2



前面的Master-Detail GridView控件應用,相信你已在市面上的書、或網路上見過,但此節中的GridView控件應用包你沒看過,但一定想過!請見圖4-8-63。

圖4-8-63


圖4-8-64


你一定很想驚呼?這是GridView嗎??不是第三方控件的效果吧?是的!這是GridView控件,而且只需要不到100行程式碼!!請先建立一個UserControl:DetailsGrid.ascx,加入一個SqlDataSource控件連結至Northwind的Order Details資料表,選取所有欄位,接著在WHERE區設定如圖4-8-65的條件。

圖4-8-65


接著加入一個GridView控件繫結至此SqlDataSource控件,並將Enable Editing打勾,然後於原始碼中鍵入4-8-17的程式碼。

程式4-8-17

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;


public
partial
class
DetailsGrid : System.Web.UI.UserControl

{


public
int OrderID

{


get

{


object o = ViewState["OrderID"];


return o == null ? -1 : (int)o;

}


set

{

ViewState["OrderID"] = value;

SqlDataSource1.SelectParameters[0].DefaultValue = value.ToString();

}

}


protected
void Page_Load(object sender, EventArgs e)

{

}

}

接著建立一個新網頁,加入SqlDataSource控件繫結至Northwind的Orders資料表,然後加入一個GridView控件,並於其欄位編輯器中加入一個TemplateField,於其內加入一個LinkButton控件,設定其屬性如圖4-8-66。

圖4-8-66


然後設定LinkButton的DataBindings如圖4-8-67。

圖4-8-67


然後於原始碼中鍵入4-8-18的程式碼。

程式4-8-18

using System;

using System.Collections.Generic;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;


public
partial
class
CollapseGridView : System.Web.UI.Page

{


private
List<int> _collaspedRows = new
List<int>();


private
List<GridViewRow> _delayAddRows = new
List<GridViewRow>();



private
bool RowIsCollasped(GridViewRow row)

{


if(_collaspedRows.Count > 0)


return _collaspedRows.Contains((int)GridView1.DataKeys[row.RowIndex].Value);


return
false;

}



private
void CreateDetailRow(GridViewRow gridRow)

{


if (RowIsCollasped(gridRow))

{


GridViewRow row = new
GridViewRow(gridRow.RowIndex, -1,

DataControlRowType.DataRow, DataControlRowState.Normal);


TableCell cell = new
TableCell();

row.Cells.Add(cell);


TableCell cell2 = new
TableCell();

cell2.Attributes["colspan"] = (GridView1.Columns.Count - 1).ToString();


Control c = LoadControl("DetailsGrid.ascx");

((DetailsGrid)c).OrderID = (int)GridView1.DataKeys[gridRow.RowIndex].Value;

cell2.Controls.Add(c);

row.Cells.Add(cell2);

_delayAddRows.Add(row);

}

}



protected
void Page_Load(object sender, EventArgs e)

{


}



protected
override
void LoadViewState(object savedState)

{


Pair state = (Pair)savedState;


base.LoadViewState(state.First);

_collaspedRows = (List<int>)state.Second;

}



protected
override
object SaveViewState()

{


Pair state = new
Pair(base.SaveViewState(), _collaspedRows);


return state;

}

}

接下來在TemplateField中的LinkButton的Click事件中鍵入4-8-19的程式碼。

程式4-8-19

protected
void LinkButton1_Click(object sender, EventArgs e)

{


LinkButton btn = (LinkButton)sender;


int key = int.Parse(btn.CommandArgument);


if (_collaspedRows.Contains(key))

{

_collaspedRows.Remove(key);

GridView1.DataBind();

}


else

{

_collaspedRows.Clear(); // clear.

_collaspedRows.Add(key);

GridView1.DataBind();

}

}

最後在GridView控件的RowCreated、PageIndexChanging事件中鍵入4-8-20的程式碼。

程式4-8-20

protected
void GridView1_RowCreated(object sender, GridViewRowEventArgs e)

{


if(e.Row.RowType == DataControlRowType.DataRow)

CreateDetailRow(e.Row);


else
if (e.Row.RowType == DataControlRowType.Pager && _delayAddRows.Count > 0)

{


for (int i = 0; i < GridView1.Rows.Count; i++)

{


if (RowIsCollasped(GridView1.Rows[i]))

{

GridView1.Controls[0].Controls.AddAt(GridView1.Rows[i].RowIndex + 2,

_delayAddRows[0]);

_delayAddRows.RemoveAt(0);

}

}

}

}



protected
void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

_collaspedRows.Clear();

}

執行後你就能看到前圖的效果了,那具體是如何做到的呢?從前面的說明,我們知道了可以在GridView控件中動態的插入一個 GridViewRow控件,而GridViewRow控件可以擁有多個Cell,每個Cell可以擁有子控件,那麼當這個子控件是一個UserControl呢 ?相信說到這份上,讀者已經知道整個程式的運行基礎及概念了,剩下的細節如LoadViewState、SaveViewState皆已在前面章節提過,看懂這個範例後!你應該也想到了其它的應用了(UserControl中放DetailsView、FormView、MultiView,哈!),對於GridView!你已經毫無疑問了!



4-8-4、GridView的效能



OK,GridView控件功能很強大,但是如果你仔細思考下GridView控件的分頁是如何做的,會發現她的做法其實隱含著一個很大的效能問題,GridView控件在分頁功能啟動的情況下,會建立一個PageDataSource物件,由這個物件負責向DataSource索取資料,於索取資料時一併傳入DataSourceSelectArgument物件,此物件中便包含了起始的列及需要的列數,看起來似乎沒啥問題嗎?其實不然,當DataSource控件不支援分頁時,PageDataSource物件只能以該DataSource所傳回的資料來做分頁,簡略的說!SqlDataSource控件是不支援分頁的,這時PageDataSource會要求SqlDataSource控件傳回資料,而SqlDataSource控件就用SelectQuery中的SQL指令向資料庫要求資料,結果便是,當該SQL指令選取100000筆資料時,SqlDataSource所傳回給PageDataSource的資料也是100000筆!!這意味著,GridView每次做資料繫結顯示時,是用100000筆資料在分頁,不管顯示的是幾筆,存在於記憶體中的都是100000筆!如果同時有10個人、100個人在使用此網頁,可想而知Server的負擔有多重了,即使有Cache加持,一樣會有100000筆資料在記憶體中!以往在ASP.NET 1.1時,可以運用DataGrid控件的CustomPaging功能來解決此問題,但GridView控件並未提供這個功能,我們該怎麼處理這個問題呢?在提出解決方案前,我們先談談GridView控件為何將這麼有用的功能移除了?答案很簡單,這個功能已經被移往DataSource控件了,這是因為DataSource控件所需服務的不只是GridView,FormView、DetailsView都需要她,而且她們都支援分頁,如果將CustomPaging直接做在這些控件上,除了控件必須有著重複的程式碼外,設計師於撰寫分頁程式時,也需針對不同的控件來處理,將這些移往DataSource控件後,便只會有一份程式碼。說來好聽,那明擺著SqlDataSource控件就不支援分頁了,那該如何解決這個問題了,答案是ObjectDataSource,這是一個支援分頁的DataSource控件,只要設定幾個屬性及對資料提供者做適當的修改後,便可以達到手動分頁的效果了。請建立一個WebiSte專案,添加一個DataSet連結到Northwind的Customers資料表,接著新增一個Class,檔名為NorthwindCustomersTableAdapter.cs,鍵入4-8-26的程式碼。

程式4-8-26

using System;

using System.ComponentModel;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;


namespace NorthwindTableAdapters

{


public
partial
class
CustomersTableAdapter

{

[System.ComponentModel.DataObjectMethodAttribute(

System.ComponentModel.DataObjectMethodType.Select, true)]


public
virtual
Northwind.CustomersDataTable GetData(int startRowIndex, int maximumRows)

{


this.Adapter.SelectCommand =


new System.Data.SqlClient.SqlCommand("SELECT {COLUMNS} FROM " +


"(SELECT {COLUMNS},ROW_NUMBER() OVER(ORDER BY {SORT}) As RowNumber FROM {TABLE} {WHERE}) {TABLE} " + "WHERE RowNumber > {START} AND RowNumber < {FETCH_SIZE}",Connection);


this.Adapter.SelectCommand.CommandText = this.Adapter.SelectCommand.CommandText.Replace("{COLUMNS}", "*");


this.Adapter.SelectCommand.CommandText = this.Adapter.SelectCommand.CommandText.Replace("{TABLE}", "Customers");


this.Adapter.SelectCommand.CommandText = this.Adapter.SelectCommand.CommandText.Replace("{SORT}", "CustomerID");


this.Adapter.SelectCommand.CommandText = this.Adapter.SelectCommand.CommandText.Replace("{WHERE}", "");


this.Adapter.SelectCommand.CommandText = this.Adapter.SelectCommand.CommandText.Replace("{START}", startRowIndex.ToString());


this.Adapter.SelectCommand.CommandText = this.Adapter.SelectCommand.CommandText.Replace("{FETCH_SIZE}", (startRowIndex+maximumRows).ToString());


Northwind.CustomersDataTable dataTable = new
Northwind.CustomersDataTable();


this.Adapter.Fill(dataTable);


return dataTable;

}



public
virtual
int GetCount(int startRowIndex, int maximumRows)

{


SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT COUNT(*) AS TOTAL_COUNT FROM Customers", Connection);

Connection.Open();


try

{


return (int)cmd.ExecuteScalar();

}


finally

{

Connection.Close();

}

}

}

}

此程式提供了兩個函式,GetData函式需要兩個參數,一個是起始的筆數,一個是選取的筆數,利用這兩個參數加上SQL Server 2005新增的RowNumber,便可以向資料庫要求傳回特定範圍的資料。那這兩個參數從何傳入的呢?當GridView向ObjectDataSource索取資料時,便會傳入這兩個參數,例如當GridView的PageSize是10時,第1頁時傳入的startRowIndex便是10,maximumRows就是10,以此類推。第二個函式是GetCount,對於GridView來說,她必須知道繫結資料的總頁數才能顯示Pager區,而此總頁數必須由資料總筆數算出,此時GridView會向PageDataSource要求資料的總筆數,而PageDataSource在DataSource控件支援分頁的情況下,會要求其提供總筆數,這時此函式就會被呼叫了。大致了解這個程式後,回到設計頁面,加入一個ObjectDataSource控件,於SELECT頁次選取帶startRowIndex及maximumRows參數的函式。

圖4-8-68


按下Next按紐後,精靈會要求我們設定參數值來源,請直接按下Finish來完成組態。

圖4-8-69


接著設定ObjectDataSource的EnablePaging屬性為True,SelectCountMethod屬性為GetCount(對應了程式4-8-26中的GetCount函式),最後放入一個GridView控件,繫結至此ObjectDataSource後將Enable Paging打勾,就完成了手動分頁的GridView範例了。

圖4-8-70


在效能比上,手動分頁的效能在資料量少時絕對比Cache來的慢,但資料量大時,手動分頁的效能及記憶體耗費就一定比Cache來的好。

Friday, August 17, 2007

另類的Silverlight中文解法

另類的Silverlight中文解法


文/黃忠成



如你所知,由於字型的關係,Silverlight目前對於雙位元文字顯示可說是困難重重,大概可歸類出兩種解法,一種是下載字型到客戶端,一種是利用Blend2將文字變成圖形,下載字型目前有法律問題的隱憂,而且一個中文字型檔大小約5MB,仍嫌過大。在上次嘗試實作DataBinding功能後,心中就有一種想法,假如於Server端將文字轉成圖形後下載到客戶端,那麼因為不是直接下載字型,所以應無法律問題(這我不確定!),也不會因下載整個字型檔而導致網頁開啟速度過慢,這樣是否就能讓前次的Data Bindigns例子支援中文的顯示呢?可惜前幾天因陪老婆考試,一直沒時間來實現心中的構想,這幾天終於有時間來實現這個架構了。基本上,實現這個架構有兩個問題必須先行解決,第一個問題是Server端如何將文字變成圖形?這不難,下列的程式便可辦到。

protected
void Page_Load(object sender, EventArgs e)

{


if (Request.QueryString["ID"] != null &&

Request.QueryString["ID"].Length > 0)

{

..................

}


else
if (Request.QueryString["Transform"] != null)

{


int index;


string column;

ResolveParams(Request.QueryString["Transform"],

out index, out column);


if (index != -1)

{


Employee data = GetData(index);


MemoryStream ms = ResolveTransform(data, column);


if (ms != null)

{

Response.Clear();

Response.BufferOutput = true;

Response.ContentType = "image/bmp";

Response.OutputStream.Write(ms.GetBuffer(), 0, (int)ms.Length);

ms.Dispose();

Response.Flush();

Response.End();

}


else

Response.End();

}

}

}



private
void ResolveParams(string transformParams, out
int index, out
string column)

{


string[] p = Request.QueryString["Transform"].Split('*');

index = -1;

column = string.Empty;


if (p.Length == 2)

{

index = int.Parse(p[0]);

column = p[1];

}

}



private
MemoryStream ResolveTransform(object data, string column)

{


PropertyInfo pi = data.GetType().GetProperty(column);


if (pi != null)


return GetDBCSJPEStream(pi.GetValue(data,null).ToString(),

new
Font("PMingLiU", 11,FontStyle.Bold), Color.Black, Color.White, 280,24);


return
null;

}



private
MemoryStream GetDBCSJPEStream(string str, Font font, Color foreColor,

Color background, int width, int height)

{


Bitmap bmp = new
Bitmap(width, height);


Graphics g = Graphics.FromImage(bmp);


Brush bFore = new
SolidBrush(foreColor);


Brush bBack = new
SolidBrush(background);

g.Clear(Color.Transparent);

g.DrawString(str, font, bFore, 2, 2);

bFore.Dispose();

bBack.Dispose();


MemoryStream ms = new
MemoryStream();

bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

bmp.Dispose();

ms.Position = 0;


return ms;

}

如果你仔細看上面的程式,會發覺其中有字體預設的問題,若要以此觀念實作一個完整的架構,關於字型的資訊應於XAML中指定才好,不過目前我只是展示這個想法的可行性,就先放著這部份不理了。第二個要解決的問題是如何於XAML中指定Data Bindings資訊,這點不難,依據前版以TAG來指定Binding Expression的概念,只需加油添醋一番,即可套用。

<Canvas
xmlns="http://schemas.microsoft.com/client/2007"

...................

<Image
Name="imgLastName"
Tag="BindingField:LastName;BindingProperty:Source;Format:Default.aspx?Transform={INDEX}*{BindingField}"
Width="300"
Height="24"
Canvas.Left="500"
Canvas.Top="23" />

</Canvas>

請注意,由於採圖形方式的緣故,這裡已不再使用TextBlock,而是使用Image控制項來顯示,SLDH.js也需稍做修改。

/////////////////////////////////////////////////////////////////////////

// Silverlight Data Binding Helper 0.1

/////////////////////////////////////////////////////////////////////////


if (!window.SilverlightBinding)

window.SilverlightBinding = {};


SilverlightBinding.BindingData = function(ctrl,bindingExpression,context)

{


var bindings = bindingExpression.split(';');


this.bindingComplete = false;


this.ctrl = ctrl;


this.context = context;


for(var i = 0; i < bindings.length; i++)

{


var temp = bindings[i].split(':');


if(temp.length != 2)

{


this.bindingComplete = false;


return;

}


if(temp[0] == 'BindingField')


this.bindingField = temp[1];


else
if(temp[0] == 'BindingProperty')


this.bindingProperty = temp[1];


else
if(temp[0] == 'Format')


this.format = temp[1];

}


this.bindingComplete = true;

}


SilverlightBinding.BindingData.prototype =

{

updateValue : function(dataItem)

{


if(this.bindingComplete)

{


if(this.format)

{


var str = eval("this.format.replace('{0}',dataItem."+this.bindingField+');');


if(this.format.indexOf("INDEX") != -1)

str = str.replace("{INDEX}",this.context.currentDataIndex);


if(this.format.indexOf("BindingField") != -1)

str = str.replace("{BindingField}",this.bindingField);

eval('this.ctrl.'+this.bindingProperty+" = str;");

}


else

eval('this.ctrl.'+this.bindingProperty+' = dataItem.'+this.bindingField+';');

}

}

}


SilverlightBinding.BindingContext = function(bindingContainer)

{


var parseBindings = bindingContainer.tag.split(';');


this.bindingComplete = false;


this.bindingContainer = bindingContainer;


this.bindingControls = new Array();


this.currentDataIndex = 0;


this.recordCount = 0;


for(var i = 0; i < parseBindings.length; i++)

{


var parseBinding = parseBindings[i].split(':');


if(parseBinding[0] == "BindingContext")

{


var bindingMethods = parseBinding[1].split(',');


if(bindingMethods.length == 2)

{


this.bindingMethod = bindingMethods[0];


this.bindingCountMethod = bindingMethods[1];


this.bindingComplete = true;

}

}


}


if(!this.bindingComplete) alert('ERROR,Binding Failed.');

}



SilverlightBinding.BindingContext.prototype =

{

_childWorker : function(parent,parseParent)

{


if(parent.tag && parent.tag != '')

{


if(parseParent)

{


var bindingData = new SilverlightBinding.BindingData(parent,parent.tag,this);


if(bindingData.bindingComplete)

{


this.bindingControls.length++;


this.bindingControls[this.bindingControls.length-1] = bindingData;

}


else


delete bindingData;

}


try

{


var temp = parent.children;

}


catch(err)

{


return;

}


for(var i = 0; i < parent.children.count; i++)


this._childWorker(parent.children.getItem(i),true);

}

},

initialize:function()

{


this._childWorker(this.bindingContainer,false);


this._receiveCount();


this._receiveData(0);

},

OnSucceeded: function(result, userContext, methodName)

{


if (methodName == userContext.bindingMethod)

{


for(var i = 0; i < userContext.bindingControls.length; i++)

userContext.bindingControls[i].updateValue(result);

}


else
if(methodName == userContext.bindingCountMethod)

userContext.recordCount = result;

},

OnFailed:function(error, userContext, methodName)

{


if(error !== null)

{

alert(error.get_message());

}

},

_receiveData: function(index)

{

eval('PageMethods.'+this.bindingMethod+'(index,this.OnSucceeded,this.OnFailed,this);');

},

_receiveCount: function()

{

eval('PageMethods.'+this.bindingCountMethod+'(this.OnSucceeded,this.OnFailed,this);');

},

next:function()

{


if(this.currentDataIndex+1 >= this.recordCount)


return;


this._receiveData(++this.currentDataIndex);

},

prev:function()

{


if(this.currentDataIndex -1 < 0)


return;


this._receiveData(--this.currentDataIndex);

}

}

下圖為執行例。



後記


這種方式僅是一個應急的解法,畢竟傳輸圖形也是需要時間的,自然不比直接使用位於客戶端的字型來的有效率。


示例下載:

http://www.dreams.idv.tw/~code6421/files/SLDataDemo2.zip

Silverlight DataBindings for 1.1 (Managed code)

Silverlight DataBindings for 1.1 (Managed code)



文/黃忠成



RC1方興未艾,RC2已在路上了,看來1.0 Release之日不遠了!前面一篇文章利用了PageMethods與JavaScript為Silverlight 1.0RC加上DataBindings的功能,此次舞台換到了Silverlight 1.1 Alpha Refresh及Visual Studio 2008 Beta 2上,與1.1時不同,這次已無法用單一的Web Site模式實作,基於ASP.NET Ajax與Silverlight所使用的CLR Runtime不同,我們必須將Silverlight與ASP.NET Ajax拆開,別誤會!這並非意味你無法將Silverlight與ASP.NET Ajax放在同一個虛擬目錄下,Silverlight 1.1使用的Binary目錄是ClientBin,ASP.NET是Bin,兩者並無衝突,限制只在於你必須將Silverlight與ASP.NET Ajax分成兩個Project來編譯,在Silverlight編譯完成後將.xaml、.js複製到ASP.NET Ajax的專案目錄下,再將.dll複製到ASP.NET Ajax的ClientBin目錄下即可。回到主題,在Silverlight 1.1中,實現Data Bindings除了可以用前一篇文章的JavaScript技巧外,還多了一個選擇,那就是使用C#等Managed的語言,SLDH.js的C#版本如下。


SLDH.cs

/////////////////////////////////////////////////////////////////////////

// Silverlight Data Binding Helper 0.1 for Silverlight 1.1 Alpha Refresh

/////////////////////////////////////////////////////////////////////////

using System;

using System.Text;

using System.IO;

using System.Net;

using System.Reflection;

using System.Linq;

using System.Collections.Generic;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Ink;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.Windows.Browser.Net;

using System.Windows.Browser.Serialization;


namespace SilverlightDataHelper

{


public
class
JSONDataRow

{


private
List<object> _columns;


private
List<object> _values;



public
object
this[int index]

{


get

{


return _values[index];

}

}



public
object
this[string name]

{


get

{


for (int i = 0; i < _columns.Count; i++)

{


if (((string)_columns[i]).Equals(name))


return _values[i];

}


return
null;

}

}



internal JSONDataRow(object[] columns, object[] values)

{

_columns = new
List<object>(columns);

_values = new
List<object>(values);

}

}



public
class
BindingData

{


private
bool _bindingComplete = false;


private
string _bindingProperty = string.Empty;


private
string _bindingField = string.Empty;


private FrameworkElement _control;


private
string _format = string.Empty;


private
PropertyInfo _cachedProp = null;



public
bool BindingComplete

{


get

{


return
this._bindingComplete;

}

}



public
string BindingProperty

{


get

{


return _bindingProperty;

}

}



public
string BindingField

{


get

{


return _bindingField;

}

}



public FrameworkElement Control

{


get

{


return _control;

}

}



public
string Format

{


get

{


return _format;

}


set

{

_format = value;

}

}



public
void UpdateValue(JSONDataRow dataItem)

{


if (_bindingComplete)

{


if (_cachedProp == null)

{

_cachedProp = _control.GetType().GetProperty(_bindingProperty);


if (_cachedProp == null)

_bindingComplete = false;

}


if (_cachedProp != null && Format != string.Empty)

{


if (_cachedProp.PropertyType == typeof(Uri))

{


Uri uri = new
Uri(string.Format(Format,

dataItem[BindingField]), UriKind.Relative);

_cachedProp.SetValue(_control, uri, null);

}


else

_cachedProp.SetValue(_control, string.Format(Format,

dataItem[BindingField]), null);

}


else
if (_cachedProp != null)

_cachedProp.SetValue(_control, dataItem[BindingField], null);

}

}



public BindingData(FrameworkElement ctrl, string bindingExpression)

{


string[] bindings = bindingExpression.Split(';');

_bindingComplete = false;

_control = ctrl;


for (int i = 0; i < bindings.Length; i++)

{


string[] temp = bindings[i].Split(':');


if (temp.Length != 2)

{

_bindingComplete = false;


return;

}


if (temp[0].ToLower() == "bindingfield")

_bindingField = temp[1];


else
if (temp[0].ToLower() == "bindingproperty")

_bindingProperty = temp[1];


else
if (temp[0].ToLower() == "format")

_format = temp[1];

}


if (_bindingField != string.Empty &&

_bindingProperty != string.Empty)

_bindingComplete = true;

}

}



public
class
BindingContext

{


private Panel _container;


private
List<BindingData> _bindingControls = null;


private
bool _bindingComplete = false;


private
int _position = 0;


private
int _count = -1;


private
string _serviceUrl = string.Empty;


private
string _bindingMethod = string.Empty;


private
string _bindingCountMethod = string.Empty;


private
string _countMethod = string.Empty;




public
int Position

{


get

{


return _position;

}


set

{


if (_position != value && value < Count && value >= 0)

{

_position = value;

UpdateBinding();

}

}

}



public
int Count

{


get

{


return _count;

}

}



public
bool BindingComplete

{


get

{


return _bindingComplete;

}

}



public
List<BindingData> BindingControls

{


get

{


if (_bindingControls == null)

_bindingControls = new
List<BindingData>();


return _bindingControls;

}

}



private
void ChildWorker(FrameworkElement elem)

{


string exprsssion = elem.Tag == null ? string.Empty : elem.Tag;


BindingData data = new
BindingData(elem, exprsssion);


if (data.BindingComplete)

BindingControls.Add(data);


if (elem is Panel)

{

Panel pnl = (Panel)elem;


for (int i = 0; i < pnl.Children.Count; i++)

{


if (pnl.Children[i] is FrameworkElement)

ChildWorker((FrameworkElement)pnl.Children[i]);

}

}

}



private
void FetchCount()

{

BrowserHttpWebRequest request =


new BrowserHttpWebRequest(new
Uri(_serviceUrl + "/" +

_bindingCountMethod, UriKind.Relative));

request.ContentType = "application/json; charset=utf-8";

request.Method = "POST";

request.ContentLength = 0;

request.Referer = System.Windows.Browser.HtmlPage.DocumentUri.AbsolutePath;

request.Accept = "/*/";


HttpWebResponse response = request.GetResponse();


StreamReader sr = new
StreamReader(response.GetResponseStream());

JavaScriptSerializer serializer = new JavaScriptSerializer();


string data = sr.ReadToEnd();

_count = serializer.Deserialize<int>(data);

sr.Close();

response.Close();

request.Close();

}



private
JSONDataRow FetchData(int index)

{

BrowserHttpWebRequest request =


new BrowserHttpWebRequest(new
Uri(_serviceUrl + "/" +

_bindingMethod, UriKind.Relative));

JavaScriptSerializer serializer = new JavaScriptSerializer();

request.ContentType = "application/json; charset=utf-8";

request.Method = "POST";

request.Referer = System.Windows.Browser.HtmlPage.DocumentUri.AbsolutePath;

request.Accept = "/*/";


Stream reqStream = request.GetRequestStream();


byte[] buff = Encoding.UTF8.GetBytes("{index:" + index.ToString() + "}");

reqStream.Write(buff, 0, buff.Length);

request.ContentLength = buff.Length;


HttpWebResponse response = request.GetResponse();


StreamReader sr = new
StreamReader(response.GetResponseStream());


string data = sr.ReadToEnd();

sr.Close();

response.Close();

request.Close();


object[] parsedData = serializer.Deserialize<object[]>(data);


return
new
JSONDataRow((object[])parsedData[0], (object[])parsedData[1]);


}



private
void UpdateBinding()

{


JSONDataRow row = FetchData(Position);


foreach (BindingData item in BindingControls)

item.UpdateValue(row);

}



public
void Initialize()

{

ChildWorker(_container);

FetchCount();

UpdateBinding();

}



public BindingContext(Panel container)

{

_container = container;


if (_container.Tag == null)

{

_bindingComplete = false;


return;

}


string[] parseBinding = container.Tag.Split(':');

_bindingComplete = false;


if (parseBinding.Length == 2 && parseBinding[0].ToLower() == "bindingcontext")

{


string[] bindingMethods = parseBinding[1].Split(',');


if (bindingMethods.Length == 3)

{

_serviceUrl = bindingMethods[0];

_bindingMethod = bindingMethods[1];

_bindingCountMethod = bindingMethods[2];

_bindingComplete = true;

}

}


if (_bindingComplete)

ChildWorker(container);

}

}

}

ㄟ...程式碼變長了哦~~~ >"<,在某些情況下,Managed Code不見得比JavaScript簡單吧!只是別忘了,這些程式碼是預先編譯後再下載到客戶端,由Silverlight CLR執行的,就理論上來說,執行效率應該比JavaScript好才對。由於Managed SLDH使用了另一種JSON格式來交換資料,所以.aspx.cs也要做一些調整。

Default.aspx.cs

using System;

using System.IO;

using System.Data;

using System.Collections.Generic;

using System.Data.SqlClient;

using System.Configuration;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Xml.Linq;

using System.Web.Services;


public
partial
class
_Default : System.Web.UI.Page

{


private
static
DataTable BuildDataCache()

{


if (HttpRuntime.Cache["DataCache_Employees"] != null)


return
HttpRuntime.Cache["DataCache_Employees"] as
DataTable;


else

{


using (SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["

ConnectionString"].ConnectionString))

{


SqlDataAdapter adapter = new
SqlDataAdapter(

"SELECT * FROM Employees ORDER BY EmployeeID", conn);


DataTable table = new
DataTable("Employees");

adapter.Fill(table);


HttpRuntime.Cache["DataCache_Employees"] = table;


return table;

}

}

}



private
static
List<object> BuildJSONRow(DataRow row)

{


List<object> result = new
List<object>();


List<string> columns = new
List<string>();


List<object> values = new
List<object>();


foreach (DataColumn col in row.Table.Columns)

{

columns.Add(col.ColumnName);

values.Add(row.IsNull(col) ? string.Empty : row[col].ToString());

}

result.Add(columns);

result.Add(values);


return result;

}


[WebMethod]


public
static
List<object> GetData(int index)

{


DataTable table = BuildDataCache();


return BuildJSONRow(table.DefaultView[index].Row);

}


[WebMethod]


public
static
int GetCount()

{


DataTable table = BuildDataCache();


return table.DefaultView.Count;

}



protected
void Page_Load(object sender, EventArgs e)

{


if (Request.QueryString["ID"] != null &&

Request.QueryString["ID"].Length > 0)

{


using (SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings[

"ConnectionString"].ConnectionString))

{

conn.Open();


SqlCommand cmd = new
SqlCommand(

"SELECT Photo FROM Employees WHERE EmployeeID = @ID", conn);

cmd.Parameters.AddWithValue("@ID", Request.QueryString["ID"]);


object data = cmd.ExecuteScalar();


if (data != null && ((byte[])data).Length > 0)

{

Response.Clear();

Response.BufferOutput = true;

Response.ContentType = "image/jpeg";


MemoryStream ms = new
MemoryStream();

ms.Write(((byte[])data), 78, ((byte[])data).Length - 78);


MemoryStream jpegms = new
MemoryStream();

System.Drawing.Image.FromStream(ms).Save(jpegms,

System.Drawing.Imaging.ImageFormat.Jpeg);

jpegms.Position = 0;

Response.OutputStream.Write(jpegms.GetBuffer(), 0, (int)jpegms.Length);

ms.Dispose();

jpegms.Dispose();

Response.Flush();

Response.End();

}

}

}

}

}

當需要做DataBindings時,只需要在.xaml.cs的Page_Loaded事件處理函式中建立此物件即可,見下面程式碼。


Page.xaml

<Canvas
x:Name="parentCanvas"


xmlns="http://schemas.microsoft.com/client/2007"


xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"


Loaded="Page_Loaded"


x:Class="SilverlightProject1.Page;assembly=ClientBin/SilverlightProject1.dll"


Width="640"


Height="480"


Background="White"

>

<Canvas
Name="DataDemo"
Height="600"
Width="800"


Tag="BindingContext:Default.aspx,GetData,GetCount">

<Canvas.Background>

<LinearGradientBrush>

<GradientStop
Color="Yellow"
Offset="0.0" />

<GradientStop
Color="Orange"
Offset="0.5" />

<GradientStop
Color="Red"
Offset="1.0" />

</LinearGradientBrush>

</Canvas.Background>

<TextBlock
Tag="BindingField:EmployeeID;BindingProperty:Text"

Name="txtEmployeeID"
Width="144"
Height="24"
Canvas.Left="166"

Canvas.Top="23"
Text="A00001"
TextWrapping="Wrap"/>

<TextBlock
Tag="BindingField:LastName;BindingProperty:Text"

Name="txtLastName"
Width="320"
Height="24"
Canvas.Left="500"

Canvas.Top="23"
Text="Alean Company"
TextWrapping="Wrap"/>

<TextBlock
Tag="BindingField:FirstName;BindingProperty:Text"
Name="txtFirstName"

Width="320"
Height="24"
Canvas.Left="166"
Canvas.Top="72"

Text="Jeffray"
TextWrapping="Wrap"/>

<TextBlock
Tag="BindingField:Title;BindingProperty:Text"

Name="txtTitle"
Width="576"
Height="24"
Canvas.Left="166"

Canvas.Top="122"
Text="Taipen 101"
TextWrapping="Wrap"/>

<TextBlock
Tag="BindingField:HireDate;BindingProperty:Text"
Name="txtHireDate"

Width="576"
Height="24"
Canvas.Left="166"
Canvas.Top="171"

Text="2005/3/4"
TextWrapping="Wrap"/>

<Image
Name="imgPhoto"

Tag="BindingField:EmployeeID;BindingProperty:Source;Format:Default.aspx?ID={0}"

Width="357"
Height="206"
Canvas.Left="400"
Canvas.Top="301">

<Image.Triggers>

<EventTrigger
RoutedEvent="Image.Loaded">

<BeginStoryboard>

<Storyboard
Name="imgAnimation">

<DoubleAnimation

Storyboard.TargetName="imgPhoto"

Storyboard.TargetProperty="Opacity"

From="0.0"
To="1.0"
Duration="0:0:6"/>

</Storyboard>

</BeginStoryboard>

</EventTrigger>

</Image.Triggers>

</Image>

<TextBlock
Name="txtLabel1"
Width="114"
Height="24"
Canvas.Left="18"

Canvas.Top="23"
Text="Employee ID:"
TextWrapping="Wrap"/>

<TextBlock
Name="txtLabel1_Copy"
Width="120"
Height="24"
Canvas.Left="349"

Canvas.Top="23"
Text="Last Name:"
TextWrapping="Wrap"/>

<TextBlock
Name="txtLabel1_Copy1"
Width="130"
Height="24"
Canvas.Left="18"

Canvas.Top="72"
Text="First Name:"
TextWrapping="Wrap"/>

<TextBlock
Name="txtLabel1_Copy2"
Width="104"
Height="24"
Canvas.Left="18"

Canvas.Top="122"
Text="Title :"
TextWrapping="Wrap"/>

<TextBlock
Name="txtLabel1_Copy3"
Width="93"
Height="24"
Canvas.Left="18"

Canvas.Top="171"
Text="Hire Date:"
TextWrapping="Wrap"/>

</Canvas>

<TextBlock
Canvas.Left="100"
Canvas.Top="200"

Text="Prev"
MouseLeftButtonDown="OnPrevClick"/>

<TextBlock
Canvas.Left="150"
Canvas.Top="200"

Text="Next"
MouseLeftButtonDown="OnNextClick"/>

</Canvas>


Page.xaml.cs

using System;

using System.Linq;

using System.Collections.Generic;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Ink;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;


namespace SilverlightProject1

{


public
partial
class
Page : Canvas

{


private SilverlightDataHelper.BindingContext _context = null;


public
void Page_Loaded(object o, EventArgs e)

{


// Required to initialize variables

InitializeComponent();

_context = new SilverlightDataHelper.BindingContext(FindName("DataDemo") as Panel);

_context.Initialize();

}



void OnPrevClick(object sender, EventArgs args)

{


if (_context.Position > 0)

{

_context.Position--;

((Storyboard)FindName("imgAnimation")).Begin();

}

}



void OnNextClick(object sender, EventArgs args)

{


if (_context.Position < _context.Count)

{

_context.Position++;

((Storyboard)FindName("imgAnimation")).Begin();

}

}

}

}

下圖是執行畫面。



http://www.dreams.idv.tw/~code6421/files/SLDataDemo_11.zip

(你需要將Northwind.mdf、Northwind_log.ldf複製到App_Data目錄下,或是修改web.config中的ConnectionString來連結到北風資料庫)