顯示具有 silverlight tutorial 標籤的文章。 顯示所有文章
顯示具有 silverlight tutorial 標籤的文章。 顯示所有文章

用 ListBox 和 DataBinding 顯示列表資料

用 ListBox 和 DataBinding 顯示列表資料 (木野狐譯)


作者: Scott Guthrie


出處: http://blog.joycode.com/scottgu/


【原文地址】Silverlight Tutorial Part 5: Using the ListBox and DataBinding to Display List Data


【原文發表日期】 Friday, February 22, 2008 5:51 AM


這是8個系列教學的第5部分,這個系列示範如何使用 Silverlight 2 的 Beta1 版本來建立一個簡單的 Digg 客戶端應用。這些教學請依次閱讀,將有助於您理解 Silverlight 的一些核心撰寫程式概念。


用 ListBox 和 DataBinding 顯示我們的 Digg 故事


前面我們使用了 DataGrid 組件來顯示我們的 Digg 故事。當我們想用多列的格式來顯示內容時,它很適合。然而對我們的 Digg 應用程式而言,也許我們想稍微改變一下頁面的顯示方式,讓它看起來不太像網格,而更像一個列表。好消息是,這很容易實現 - 並且我們不需要改變任何程式程式碼。


首先我們將 DataGrid 組件替換為 <ListBox> 組件。我們保持原有的組件名稱 ("StoriesList"):


重新執行一下程式,搜尋故事,ListBox 會顯示搜尋結果如下:




你可能覺得奇怪 - 為什麼每個紀錄都變成了 "DiggSample.DiggStory"? 這是因為我們把 DiggStory 對像綁定給了 ListBox(而綁定的預設行為會叫用這些對象的 ToString() 方法)。如果我們想改用每個 DiggStory 對象的 Title 屬性來顯示紀錄,可以設定 ListBox 的 DisplayMemberPath 屬性:


這樣做之後的效果如下:




如果要每次顯示不止一個值,或者定制每個紀錄的佈局,我們可以覆蓋 ListBox 組件的 ItemTemplate,並提供一個自訂的 DataTemplate. 然後在這個 DataTemplate 內,定制每個 DiggStory 對像如何顯示。




例如,我們可以用 DataTemplate 同時顯示 DiggStory 的 Title 和 NumDiggs 值,如下所示:




在 DataTemplate 中,我們可以綁定 DiggStory 對像中我們所需的任何公共屬性。注意上面我們是如何用 {Binding 屬性名} 語法,配合兩個 TextBlock 組件來完成這一點的。




設定了上述 DataTemplate 後,我們的 ListBox 會顯示如下:




讓我們再進一步,修改 DataTemplate 的定義如下。其中使用了兩個 StackPanel - 一個用於水平地堆疊行,另一個用來垂直地堆疊文字塊(TextBlock)。




上述 DataTemplate 會使我們的 ListBox 用如下方式顯示紀錄:




我們在 App.xaml 檔案中定義如下的 Style 規則(注意如何使用 LinearGradientBrush 來獲得 DiggPanel 上的好看的漸變背景效果):




關於 ListBox 有一點值得注意 - 即使我們定制了其紀錄的顯示方式,它仍然會提供懸浮以及選中狀態的語義,不管你使用的是滑鼠游標還是鍵盤(上/下方向鍵,Home/End,等):




ListBox 還支援完整的流式改變大小的功能 - 並在需要的時候提供內容的自動捲動功能(注意當視窗變小時,水平捲動條是如何出現的):


下一步


我們現在已經把資料的顯示切換成了基於列表的方式,並清理了其內容列表。




(翻譯:木野狐)


本文章來自於神魂顛倒論壇 http://bbs.flash2u.com.tw


原文網址:http://bbs.flash2u.com.tw/dispbbs_220_83693_2.html

Silverlight 模擬的 Surface 效果



40 分鐘內演示 31 項微軟技術 的視訊中,看到了這個透過 Silverlight 模擬出來的 Surface 效果:手指拉伸縮放圖片。

存取以下地址即可體驗,語言為法語,體驗之前必須安裝 Silverlight
http://galilee.microsoft.fr/TechDays2008/SL/techdays-2008-silverlight.aspx

讓你對 Silverlight 更感興趣 -- Silverlight 1.0 Fire Starter


讓你對 Silverlight 更感興趣 -- Silverlight 1.0 Fire Starter

如果你對 Silverlight 感興趣,或者想瞭解更多,這個網站值得看看:


整個網站是由 Silverlight 構建的,共有 8 段關於 Silverlight 的視訊(也可以下載):介紹 Silverlight, Silverlight 開發, 開發故事, Popfly 和 Silverlight, Silverlight 的未來等。

Live@edu 網站更新,並採用 Silverlight




Live@edu 網站更新,並採用 Silverlight




Live@edu 是微軟的校園 Windows Live 計劃,輔助學生更好的使用 Windows Live 服務產品(桌面,線上,移動)。主要服務產品有 Hotmail, Messenger, SkyDrive, Spaces, Office Live Workspaces, Writer, Mobile。最近其網站更新了,並採用了 Silverlight 技術。




存取:http://my.liveatedu.com/

用Visual Studio 2008進行Silverlight開發



微軟


Silverlight
瀏覽器外掛
使得開發者能夠執行富因特網程式(RIAs)--包括動畫,向量圖形和視訊回放等等。看看如何進行Silverlight開發,並且感受一下這種新的開發方式吧。本文程式碼下載:http://assets.devx.com/sourcecode/20341.zip


  經過多年發展,我們看到了Web應用程式的繁榮。早期的Web網站僅僅支援靜態的HTML頁面,圖片和文字訊息。然後,伺服器端技術如CGI, ASP和JSP等使得Web硬喲程式變成了現實,使用者突然可以在Web上做很多事情了,比如線上購買商品,預訂等等。客戶端技術如Javascript等輔助提高了使用者的Web應用體驗,使得它們更加具備響應性。儘管AJAX的相關技術已經成熟很多年了,但也就是在最近幾年人們才開始花費大量時間開發 AJAX的Web應用程式。所有這一切都是為了同一個目標--使得Web應用程式交互性和響應能力更強。


  今天,又出現了一個新名詞--RIA,是Rich Internet Applications的縮寫。對於微軟來說,RIA實際代表著Rich Interactive Applications。微軟最近啟動了一個相關的技術/產品名為Silverlight。原名為Windows Presentation Foundation/Everywhere(WPF/E)的Silverlight是一個瀏覽器外掛,能夠使得開發者建立RIA程式包括動畫,向量圖形和視訊回放等等。


  這篇文章輔助你瞭解Silverlight的開發,希望給你一個很好的關於Silverlight開發的講解。


  

Silverlight
現狀


  目前,有兩個版本的Silverlight:1.0(發佈版)和1.1(alpha發佈),主要的區別在於是否支援.NET語言1.1版本。對於1.0版本,你必須使用Javascript來寫你的程式邏輯。在1.1版本裡,你可以使用C#或者VB進行程式邏輯開發,通過CLR來執行。


  Silverlight執行時目前支援下列瀏覽器:


  ‧ Internet Explorer 6/7


  ‧ Firefox 1.5/2.0


  ‧ Safari 2.0


  本文著重講解Silverlight1.1的內容。


  取得開發工具


  為了開發Silverlight應用程式,你必須獲得以下執行時/工具:


  執行時:


  為了在瀏覽器裡檢視Silverlight應用程式,下載如下內容:


  Microsoft Silverlight 1.0 Release Candidate


  ‧ Mac


  ‧ Windows


  ‧ Microsoft Silverlight 1.1 Alpha Refresh


  ‧ Mac


  ‧ Windows


  ‧ Microsoft ASP.NET Futures (July 2007)


  ASP.NET Futures下載包含了用於支援Silverlight程式的最新ASP.NET控制項。


  開發工具:


  正式版已出 VS 2008正式版開發工具開放下載Visual Studio 2008 有哪些版本


  當你下載並安裝了VS2008之後,下載Microsoft Silverlight Tools Alpha Refresh for Visual Studio (July 2007),這是一個用來建立Silverlight程式的VS2008增強包。安裝它會為VS2008Beta2新增如下特性:NET 3.5和VS 2008中的ASP.NET AJAX



  1. VB和C#工程模板

  2. IntelliSense和XAML程式碼產生器

  3. Silverlight程式的調試

  4. Web引用支援

  5. 和Expression Blend的集成


  6. VS 2008一些Web開發新特性


  另外,你還需要如下專業工具來進行Silverlight開發:


  ‧ Expression Blend 2.5 Preview: 專業級Silverlight使用者交互開發工具(Expression Blend 2 十二月 預覽版


  ‧ Expression Media Encoder Preview Update: Microsoft Expression Media的特性之一,允許你建立和增強視訊


  ‧ Expression Design: 用來建立Silverlight程式的專業插圖和繪圖設計工具。


  最後,你需要下載下列包含文檔和例程程式碼的SDK :


  ‧ Microsoft Silverlight 1.0 Software Development Kit Release Candidate


  ‧ Microsoft Silverlight 1.1 Software Development Kit Alpha Refresh


  開始撰寫程式


  當安裝好上述工具之後,你可以建立你的第一個Silverlight程式了。打開VS2008,建立一個新工程。工程類型選擇 Silverlight,選擇Silverlight工程模板:如圖1所示。將工程命名為OurFirstSilverlightProject。









在Solution Explorer中,點選Show All Files按鈕來檢視所有VS自動產生的程式碼。圖2顯示了所有檔案。





圖2


  下面一節包含了該Silverlight工程裡的基本檔案的講解:


  TestPage.html


  這是一個測試頁,用來測試Silverlight程式。它包含了Silverlight控制項並引用了兩個JavaScript檔案:Silverlight.js和TestPage.html.js。下面是Testpage.html的內容:









以下是引用片段:


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


<html xmlns="http://www.w3.org/1999/xhtml" >


<!-- saved from url=(0014)about:internet -->


<head>


<title>Silverlight Project Test Page </title>




<script type="text/javascript" src="Silverlight.js"></script>


<script type="text/javascript" src="TestPage.html.js"></script>


<style type="text/css">


.silverlightHost { width: 640px; height: 480px; }


</style>


</head>




<body>


<div id="SilverlightControlHost" class="silverlightHost" >


<script type="text/javascript">


createSilverlight();


</script>


</div>


</body>


</html>



  包含Siverlight控制項的HTML頁面頁可以包含通常的HTML元素來構成一個web頁面。當你雙擊Solution Explorer中的Testpage.html,VS2008將會在一個分離視圖裡展示頁面,這是VS2008的新特性。使用分離視圖,你可以在瀏覽 HTML程式碼時同時預覽它在瀏覽器中的效果。如圖3.





圖3


  TestPage.html.js


  這個檔案包含了一個Javascript函數,裝載Silverlight控制項到web頁上。它也引用了一個包含Silverlight程式的使用者界面定義的XAML檔案。



以下是引用片段:


  // JScript source code


  //contains calls to silverlight.js, example below loads Page.xaml


  function createSilverlight()


  {


  Silverlight.createObjectEx({


  source: "Page.xaml",


  parentElement: document.getElementById("SilverlightControlHost"),


  id: "SilverlightControl",


  properties: {


  width: "100%",


  height: "100%",


  version: "1.1",


  enableHtmlAccess: "true"


  },


  events: {}


  });


  // Give the keyboard focus to the Silverlight control by default


  document.body.onload = function() {


  var silverlightControl = document.getElementById('SilverlightControl');


  if (silverlightControl)


  silverlightControl.focus();


  }


  }

優化 Silverlight 的安裝體驗

摘要


Microsoft Silverlight 是一個跨瀏覽器、跨平台的外掛程式,實現了次世代以 .NET 為基礎的多媒體體驗,以及豐富的網頁互動式應用程式。在透過瀏覽器閱覽 Silverlight 內容時,使用者會被要求在他們的電腦上,下載並安裝 Silverlight 外掛程式。因此,若想要在網站上使用 Silverlight 外掛程式來發表豐富的內容和資訊,就必須要再建立一個安裝體驗,以鼓勵使用者啟動、同意,並完成 Silverlight 安裝程序。該體驗必須能提醒使用者為什麼他們要安裝 Silverlight,並向使用者表明網站信賴 Silverlight,且能移除安裝及使用 Silverlight 的阻礙。


定義



  • 預定體驗(Default Experience )- 當使用者使用已經安裝了適當版本的 Silverlight 瀏覽器來閱覽具有 Silverlight 功能的網頁時,將會看到的畫面。

  • 安裝體驗(Installation Experience)- 當使用者使用未安裝適當版本的 Silverlight 瀏覽器來閱覽具有 Silverlight 功能的網頁時,將會看到的畫面。


實現令人信服的 Silverlight 安裝體驗


欲實現令人信服的 Silverlight 安裝體驗,可經由下列三個步驟來完成:



  • 設計您網頁的預定體驗。

  • 依據預定體驗設計您網頁的安裝體驗。

  • 將兩個體驗疊在一起。


設計目標



  • 傳達在文件內容中的價值,只要安裝了 Silverlight 就能夠獲得。

  • 提供一個明確的呼求,請使用者採取行動安裝 Silverlight。

  • 消除阻礙使用者完成安裝的疑慮。


高階設計指導原則



  • 提供一個窺探或指示,具 Silverlight 功能的內容看起來像什麼。

  • 傳達給使用者,他們必須「取得 Silverlight」才能獲得應有的體驗。

  • 使用完整的 Silverlight 提供的安裝提示,以確保使用者能有前後一致的體驗。


設計預定體驗


我們將使用一個簡單的網站來當範例,該網站使用了 Silverlight 品牌標示並展示了一段有趣的影片。網站將描述本文件所提出的設計建議。網站的預定體驗擷取畫面如下:


圖片點選可在新視窗打開檢視


繼續閱讀:


http://bbs.flash2u.com.tw/dispbbs_220_82260_1.html

Blend 2 與 Silverlight 2 教學

包含按鈕的製作詳解與範例下載


http://www.nibblestutorials.net/


SilverLight中文完全解決方案


下面這篇出自MSDN的文章,詳細介紹了SilverLight中文遇到的問題與解法。




問題的起源是Silverlight的Runtime中沒有內嵌中文字型,而解法簡單地說,有下列三種:




1.下載字型或是 ODTTF(XPS)


2.Path


3.圖型




文中認為最終極的解法不是在Runtime中內嵌中文字型(因為會過於肥大),最好的解法仍是下載字型,不過目前這個作法會有版權上的問題,因此文中除提供免費字型的下載點之外,也指出微軟也可能提供免費下載的字型,以解決這個困境。




http://www.microsoft.com/taiwan/msdn/columns/huang_jhong_cheng/Silverlight_cht_solutions.htm


探討 XAML 物件的填色技巧-使用 Blend 2 的筆刷工具


影片目的說明:



  • 說明 Blend 2 筆刷工具的種類及其用途。

  • 示範如何使用筆刷工具與 Brush Transform 工具,並說明填色時所需注意的重點。

  • 說明設定線性漸層、放射狀漸層、與漸層選項的方法及其用途。


適合的聽眾:Silverlight 初學者,Blend 2 設計工具初學者


影片下載:http://download.microsoft.com/download/9/6/1/9610a252-d419-4ff0-82a3-6b316827fd69/SilverlightVideoClass02.zip

應用 Expression Encoder 發佈 Silverlight Streaming 視訊

應用 Expression Encoder 發佈 Silverlight Streaming 視訊

Expression 套件中的 Expression Media Encoder 將變為 Expression Encoder, 現在的 preview 版本已經提供了類似於Windows Media Server 的視訊流發佈功能,如下將介紹一下如何在沒有安裝 Windows Media Service 的情況下,利用 Expression Encoder 發佈視訊流,並且用 Silverlight 進行展現。

1. 從 Live Encoding Mode 開始

进入Live Encoding模式

a. Live Encoding Mode

Expression Encoder 將提供一個 Live Encoding Mode, 可以從"View(視圖)" 選單選擇進入 Live Encoding Mode。

在 Live Encoding Mode 中你可以選擇視訊以及音頻捕獲設備,進行時時的編碼,也可以選擇已經存在的視訊檔案進行 Streaming。

2. 選擇輸出訊息/屬性

选择输出格式

b. 輸出格式設定

你可以通過輸出面板設定發佈在本機的輸出通訊埠,最大連結數目,也可以將發佈點設定到其它 Server 上。

你也可以將時時捕獲的視訊信號進行存檔,放在指定的目錄中。

image

c. 設定碼流屬性

设置Metadata

d. 設定 Metadata

3. 使用 Windows Media Player 進行測試

image

e. 測試 MMS 源

播放成功時,Expression Encoder 的 Connection count (連結數目)會顯示為1.

4. 利用 Silverlight 發佈網站

image

f. 選擇 Silverlight Player 模板

在 Expression Encoder 中,你可以選擇非 Live 模式對模板進行選擇發佈,之後在本地的 IIS 中把相應檔案夾設定為虛擬目錄,對 StartPlayer.js 檔案做如下變更:

function get_mediainfo(mediainfoIndex) {
switch (mediainfoIndex) {

case 0:
return { "mediaUrl": "mms://10.86.16.17:8080/",
"placeholderImage": "",
"chapters": [
] };
default:
throw Error.invalidOperation("No such mediainfo");
}
}

大功告成,馬上分享你的 Silverlight 視訊直播吧~

Expression Encoder最佳化影片


Expression Encoder最佳化影片


Microsoft Expression Encoder - VC-1內容編碼器


Expression Encoder的設定方式如下:1.首先打開Expression Encoder,並匯入wmv影片。2.將Video編碼選項設定為Stream Board(MP)或Stream Board(AP)3.調整Width及Height,因為Encoder預設自動縮小影片尺寸,記得要調回原來影片的尺寸。

Expression Encoder 英文說明

不然就看 yahoo的翻譯,不過翻譯的很難閱讀:
http://tw.search.yahoo.com/language/translatedPage?tt=url&text=http%3a//www.microsoft.com/expression/products/overview.aspx%3fkey=encoder&lp=en_zt&.intl=tw&fr=sfp

微軟Expression Encoder 是Windows Media Encoder的後繼產品。

Windows Media Encoder是一個適用於希望充分利用 Windows Media 9 系列中的許多創新功能(包括高質量多聲道聲音、高清晰度視訊質量、新增對混合模式聲音和音樂內容的支援)的內容建立者的強大工具。

全功能版Expression Encoder可以免費試用60天,對顯示系統要求較高:DirectX 9.0顯卡,支援Pixel Shader 2.0,256 MB以上顯存,如:ATI Radeon X300 或 NVIDIA GeForce 5600層級顯卡以上,否則無法正常編碼。

可以到 這裡 下載

將3DS和DXF格式轉換成XAML

將3DS和DXF格式轉換成XAML

Autodesk 公司的 3ds Max 是製作 3D 模型比較的工具,目前,Electric Rain 公司發佈了 ZAM 3D 產品,可以為Microsft Windows Vista 應用程式的開發者和設計者建立 3D 界面的元素提供快速而簡便的解決方案。

另外,它還可以將3ds和dxf格式的檔案轉成XAML格式。可與Microsoft Expression Blend 整合。

相關的下載和教學
http://www.erain.com/products/ZAM3D/DefaultPDC.asp

Swift 3D 5.0 版增加了與 Microsoft Silverlight 的整合



Swift 3D 5.0 版增加了與 Microsoft Silverlight 的整合

可以直接匯出成Microsoft Silverlight 和 Windows Presentation Foundation(WPF) 使用的3D 場景

Mix07 Keynote Silverlight DEMO (含原始碼下載)


Mix07 Keynote Silverlight DEMO (含原始碼下載)
原始碼路徑

XAML 內部




XAML 內部





Silverlight XAML 支援多種形狀,能夠合成複雜的對象。支援的基本圖形包括矩形、橢圓、線條、多邊形、復合線和路徑。它們大多數都是不解自明的。復合線允許定義一系列相連的線段。路徑允許定義一個通過 Canvas 的非線性路徑(如同塗鴉)。



畫筆決定如何在螢幕上繪製對象。用 Fill 繪製內容,用 Stroke 繪製輪廓。畫筆分純色畫筆、漸變畫筆和圖像畫筆幾種。純色畫筆通過 fill 屬性(如前例使用的 Fill="Black")的固定色、或使用 SolidColorBrush 作為附加屬性實現(如下所示):













顏色可以通過名稱(支援 141 種命名的顏色)或十六進位 RGB 定義。






漸變畫筆通過在規範化空間中定義漸變域和若干漸變停留來實現。舉例來說,假設在灰色陰影中,需要一個線形漸變,從右至左,從黑變白。指定漸變停留 0(規範化線的開端)為黑色、漸變停留 1(規範化線的結束)為白色。Silverlight 就將為您繪製這個漸變。漸變也可以在二維空間中用規範化矩形定義空間來繪製(0,0 為左上,1,1 為右下)。要定義一個二維的填充矩形,左上為紅色,右下為黑色,中間是流暢的漸變,使用 XAML 如下:







用 ImageBrushes 也可以繪製對象,圖像將被適當地剪切或拉伸。因此,例如可以指定使用 ImageBrush 填充橢圓,使用的 XAML 如下:






在 XAML 中,文件可以用 TextBlock 標記呈現。這樣您可以控制文件的各個方面,如內容、字體、字號、折行等等。以下是一些範例:




此外,Silverlight 支援用於實現文件輸入的鍵盤事件。在根元素上可以定義鍵盤事件(KeyDown 或 KeyUp),並使用事件參數獲知按下的是哪個鍵。








XAML 概述



XAML 概述
XAML 是一種基於 XML 語言,可用於定義圖形資源、使用者界面、行為、動畫等。微軟將它作為在 Windows Presentation Foundation 中使用的標記語言推出。Windows Presentation Foundation 是一種面向桌面的技術,屬於 .NET Framework 3.0 的一部分,旨在輔助協調設計人員和開發人員在建立應用程式時的工作。
一直以來,設計人員使用一套工具和資源建立應用程式,而開發人員則使用自己的另一套工具。工具集的不符合可能對最終的應用程式產生負面影響。微軟推出新的 Expression 工具套件,主要是 Microsoft ExpressionR Design 和 Microsoft Expression Blend,讓專業設計人員可以分別將圖形項目和使用者界面放在一起,將最終結果表述為 XAML,以便開發人員用此構建應用程式。
首次發佈的 Silverlight 所使用的 XAML 不同於 Windows Presentation Foundation 使用的 XAML,前者是可用於桌面的完整 XAML 的面向 Web 子集。因此,如果您熟悉 Windows Presentation Foundation XAML,您可能會注意到缺失一些東西,比如  標記、頁面資源、資料綁定和豐富組件模型。
在 XAML 中,元素是用 XML 標記定義的。每個 Silverlight 文檔的根層級都是 Canvas 標記,它定義繪製 UI 元素的空間。該 Canvas 應包含 Silverlight 需要的 XML 命名空間聲明。
一個 Canvas 可以有一或多個子項,子 Canvases 又可以建立它們自己的子項。Canvas 子項有相對於其父項的位置,而不是對根 Canvas。下面的範例中,一個 Canvas 包含一個矩形 (Rectangle),該矩形放在距其父項左上角 25 像素的位置。

Silverlight的Ink功能


Silverlight的Ink功能

這是Silverlight支援的Ink功能,一種俗稱數位墨水的技術,它能夠捕捉使用者利用數位筆或是滑鼠等輸入裝置,在螢幕上所描繪的路徑,並且將其顯示出來,摸擬手寫筆跡的功能。 



由於Silverlight支援Ink功能,因此你可以透過Silverlight,實作出Web版的數位墨水功能,讓使用者在網頁上書寫文字或是描繪圖形。有了Ink功能,相信將來一旦我成為大人物之後,就不用擔心每天簽不完的名了,只要透過網路,就可以輕易的將我的手寫簽名傳遞到全世界給我的仰慕者呀,想想真是幸福啊。



一個Silverlight Slideshow相本範例


一個Silverlight Slideshow相本範例

網站名稱:First Floor網址:http://www.firstfloorsoftware.com/Default.aspx有一個不錯的Silverlight Spy工具


有下列主要功能:

Convenient XAML object explorer
XAML object property grid allows for getting and settings property values
Regeneration of the XAML xml based on the object model
Statistics of used objects
Tracing facility for debugging Silverlight 1.0 applications


還有一個Silverlight Slideshow的相本範例,可以參考


提高 Silverlight 應用程式性能


提高 Silverlight 應用程式性能


本文講述使 Microsoft Silverlight 應用程式快速、流暢執行的性能小提示。

主要性能提示:

多種平台和瀏覽器上的測試
在開發期間將 EnableFrameRateCounter 設定為 true
Silverlight 外掛盡量少用透明背景
使用 Silverlight 動畫,而不是自己建立每影格組成的動畫
避免對文字大小使用動畫
避免使用 Windowless(無視窗)模式
將可能使用可見性而不使用不透明度
Silverlight 使用多核呈現和媒體回放
在全螢幕模式下,隱藏不用的對象
不要對 MediaElement 對像使用 Width 和 Height 屬性
不要對 Path 對像使用 Width 和 Height 屬性
當 Downloader(下載器) 結束時,分離事件並設定為 null
將 CPU 密集的工作拆分成更小的任務


多種平台和瀏覽器上的測試


如果你正在為多種操作系統(例如 Macintosh 和 Windows)和多種瀏覽器(例如Microsoft Internet Explorer、Mozilla FireFox 和 Apple Safari)開發基於 Silverlight 的應用程式,千萬要記住使用你要部署的操作系統和瀏覽器進行一般測試。不同系統和瀏覽器之間行為的不同和 Silverlight 處理這些行為的程式碼會影響程式性能。尤其是你的應用程式有嵌入的透明背景外掛和使用大量 JavaScript 程式碼的時候,應當進行全面測試。

在開發期間將 EnableFrameRateCounter 設定為 true


外掛的呈現性能隨指定的宿主參數和內容的複雜程度而變化。我們推薦你在程式開發期間將 EnableFrameRateCounter 屬性設定為 true,這個設定將在瀏覽器的狀態欄裡顯示呈現的 Silverlight 內容的影格速率(fps,frames-per-second),這樣,你就能為你的應用程式調優。

Silverlight 外掛盡量少用透明背景


透明背景或許是很有用的,例如,當你嵌入的 Silverlight 外掛包含一個非矩形的形狀如汽車的照片時,你不想顯示汽車周圍的矩形內容。你可以設定透明的 Silverlight 外掛背景只讓汽車的圖片顯示出來。然而,使用透明的 Silverlight 外掛背景對性能有重大影響,因此,應盡可能地避免使用這種功能。

使用 Silverlight 動畫而不是自己建立每影格組成的動畫


使用 Silverlight 外掛內嵌的動畫比你使用 JavaScript 建立自己的每影格動畫要快的多。 隨時間推移使用元素樹的推薦做法是使用動畫系統。這種方法是與平台和瀏覽器無關的,並且是最有效的。

避免對文字大小使用動畫


對文字大小進行設定動畫潛在地會使用大量系統資源。這是因為 Silverlight 在呈現文字時使用 hinting(字體微調) 平滑文字技術。如果如果對文字大小設定動畫(通過 Transform 對像或者 FontSize 屬性), Silverlight 對每影格都進行微調,這會導致資源的浪費,也可能會導致影格的丟失。 如果你的程式需要動態修改文字大小,最好使用向量圖形代替文字。

避免使用 Windowless(無視窗)模式


只在必要時才設定 Windowless 屬性為 true ,Windowless 模式是很費資源的,可能導致動畫的破裂。

盡可能使用 Visibility(可視性) 而不使用 Opacity(不透明度)


如果你想簡單地讓對象可見或不可見而不是使用部分不透明度或者淡出淡入對象,請使用 Visibility 屬性而不使用 Opacity 屬性。Opacity 意味著較高的代價,這是因為,對像仍然是可點選的,並且需要呈現。將 Visibility 設定為 Collapsed 可避免這些問題。

Silverlight 使用多核呈現和媒體回放


Silverlight 利用多核的優點進行內容呈現和媒體回放。因此,你的 Silverlight 程式在多核系統上表現得會更好。

在全螢幕模式下,隱藏不用的對象


當程式進入到全螢幕模式時,隱藏所有在全螢幕模式下不需要呈現的對象,或者從元素樹中斷開

他們。你可以將對象的 Visibility 屬性設定為 Collapsed。

不要使用 MediaElement 對象的 Width 和 Height 屬性


盡量避免明確設定 MediaElement 對象的 width 和 height 屬性。相反,讓媒體元素以它原本的大小顯示,如果你需要這些元素的顯示大小,最好使用媒體編碼工具重新將媒體編碼成期望的大小。

不要使用 Path 對象的 Width 和 Height 屬性


不要設定 Path 對象的 Width 和 Height 屬性。設定這些屬性會導致額外的拉伸,影響性能。相反,明確設定 Path 對象的座標控制它的形狀和位置。

當 Downloader(下載器)完成時,分離對象並設定為 null


當你使用 Downloader 對像時,當 Completed 事件觸發後,分離掉 Downloader 的所有事件處理器,然後將 Downloader 設定為 null。

將 CPU 密集的工作切分成更小的任務


當 JavaScript 執行時,外掛停止呈現。通常,在事件處理器中做點少量的工作時,這不是什麼問題。然而,如果你的程式需要在 JavaScript 線程上執行大量的CPU 密集的工作,我們建議你將這個工作劃分為更小的任務。這將會保持期望的影格速率進行呈現。

Balder 3D Engine for Silverlight

Balder 3D Engine for Silverlight

Balder 3D Engine for Silverlight是以Silverlight 1.1為基礎打造的,並且是Open Source!!

http://www.codeplex.com/Balder
3D 很可能是很多人選擇 Silverlight 的第一個誘因,不妨看看 Silverlight / WPF 在 3D 方面的應用表現

什麼是 Silverlight Streaming ?

什麼是 Silverlight Streaming ?

http://silverlight।live.com/

Microsoft® Silverlight™ Streaming by Windows Live™ is a companion service for Silverlight that makes it easier for developers and designers to deliver and scale rich media as part of their Silverlight applications। The service offers web designers and developers a free and convenient solution for hosting and streaming cross-platform, cross-browser media experiences and rich interactive applications that run on Windows™ and Mac. Combined with the ability to create content with Microsoft® Expression Studio and other 3rd party tools, Web designers and content publishers wishing to integrate Silverlight applications into their online properties can enjoy complete control of the end user experience.

還有免費的4GB空間可以申請
http://silverlight.live.com/account/create.aspx


Silverlight Streaming 案例 DEMO

Halo 3 Interactive Game ManualBefore you play the game, master all the controls, weapons, and gameplay modes in the Halo 3 Interactive Game Manual.

Partner-TV: Telling it how it isPartner-TV provides Sales, Marketing and Technical information to Microsoft’s Partners throughout the UK and beyond.

Roxio BuzzRoxio Buzz makes publishing video clips and photo-slideshows to the Web fun and easy, now updated with support for Silverlight Streaming।

一些相關資源

About Silverlight Streaming: To learn more about the benefits of Microsoft® Silverlight™ Streaming by Windows Live™, visit the Silverlight Streaming page on microsoft.com/silverlight.

For Developers and Designers: To learn more about how to program Microsoft® Silverlight™ Streaming by Windows Live™ please review the SDK on dev.live.com/silverlight.

Learn about Microsoft Silverlight: Explore the possibilities of Microsoft® Silverlight™, a cross-browser, cross-platform plug-in for delivering the next generation of media experiences and rich interactive applications (RIAs) for the Web, visit microsoft.com/silverlight.

使用上若有疑問,也可以參考這邊的設定玩玩Silverlight streaming


http://61.30.28.35/ajun/archive/2007/06/20/51452.aspx
如果你裝了Microsoft Expression Media Encoder Preview後卻發現沒有template的話主要是語系的問題,直接將安裝資料夾中的Template\en的資料夾複製一份並命名為zh-tw(如果你的是繁體中文的作業系統的話),(Template放置的資料夾 : C:\Program Files\Microsoft Expression\Media Encoder 1.0\Templates\en)

manifest.xml

StartWithParentMicrosoftAjax।jsPreviewMedia।jsEmePlayer.jsplayer.jsstartPlayer.js


Silverlight 完全中文解決方案

Silverlight 完全中文解決方案

作者:黃忠成

問題的起源
如你所知,Silverlight 具備相當完善的 2D 向量繪圖及動畫能力,而且擁有了通往 RIA 世界最重要的完整程式架構支援,但是一旦想將其應用在實務的網頁開發上時,你馬上會陷入到 Silverlight 目前無法顯示中文的窘境之中!!事實上,Silverlight 在顯示中文上並沒有問題,只是其 Runtime 並未內建中文字型,導致所有的中文字都會因缺乏字型的緣故而顯示成一個個的小方框,解決這個問題的方案也不是沒有,本文就一一細數目前在 Silverligh 上顯示中文的解決方案。

解法一:下載字型或是 ODTTF(XPS)
雖然 Silverlight Runtime 中未內建中文字型,不過倒是提供了字型下載的功能,Silverlight Runtime 支援 TTF 及 ODTTF(XPS) 等兩種字型,我們可以使用 Downloader 物件來下載包含字型的 ZIP 檔案,然後以 setFontSource 函式將字型指定給 TextBlock,如此便能顯示中文字了,詳細的做法可以參考 Silverlight SDK 的說明文件。但如你所知的,字型本身有著授權的問題,你不能下載未經授權的字型到客戶端,這意味著除非微軟同意,否則我們不能在網站上提供如 Windows 之細明體、標楷體等字型下載,當然!轉成 XPS 後所粹取出的 ODTTF 也是受到同樣限制的。

解法二:Path
微軟的周旺暾先生提出了下載字型外的另一種解法,那就是使用 Path 物件,他提出了兩種使用 Path 物件來顯示中文的方法,一是使用 Blend 將中文直接轉成 Path,這個方法的確可行,但只適用於靜態字之顯示。二是於網站伺服器上安裝 .NET Framework 3.0,利用 WPF API 動態將指定文字轉成 Path 後回傳給客戶端,此法可適用於靜態或是動態之文字顯示,詳細請參考旺暾兄之 Blog:http://blogs.msdn.com/wtchou/

解法三:圖型
圖形解法是我於前幾個月所提出的解法,簡單的說就是在伺服器端將文字輸出成圖形,回傳至客戶端指定給 Image 物件來顯示中文,詳細請參考我的 Blog:http://blog.csdn.net/Code6421/archive/2007/08/09/1733745.aspx

為何不在 Runtime 內嵌中文字型?
老實說,除了下載字型外,使用 Path 或是圖形都只能算暫解燃眉之急的解法,畢竟 TextBlock 控件才是 Silverlight 用來顯示文字的主要控件,以 Path 來說,雖然支援換行上不是問題,但是若要兩行顏色或是字體不同,那就傷腦筋了!圖形也有著同樣的問題,如何算出輸出文字後圖形的大小,頁面上又該如何調配都是問題,即使能夠克服,也必須花上不少時間!總歸一句話,只要 Silverlight Runtime 內嵌中文字型,一切的問題都迎刃而解,但這樣一來,Silverlight Runtime 就不可能低於 2MB,畢竟中文字博大精深,每個字型檔少說都要 8~9MB,就算用 ZIP 壓縮後也要 4~5MB,更不用談要支援繁簡兩種字型了,若再將其它語系算進去的話,那這個 Runtime 可以說是大怪物一隻了,別忘了!Silverlight Runtime 是要能夠執行於所有語系之系統上的!因此,Silverlight Runtime 內嵌中文字型的方式在實務上是不可行的,那又該如何是好呢?我認為應該循視情況下載字型的方向走,當觀看一個繁體中文的 Silverlight 網頁時,若使用者的 Silverlight Runtime 未下載所需要的字型,那麼就提示該使用者並自動由某一網站下載字型,這個某一網站可以是開發者的,也可以是微軟的,不過!這個假設建立在一個前題之下,那就是下載字型的動作必須是合法的。

評估使用免費字型的可能性
好了!你現在應該由抱怨微軟不在 Silverlight Runtime 內嵌中文字型慢慢轉成抱怨微軟不在推出 Silverlight Runtime 時開放某些中文字型的授權了,事實上!就我所得到的消息,微軟目前正在研擬修改字型授權,未來各位可能可以將某些特定字型放在 Silverlight 網站上供人下載或是由微軟網站下載而不觸法,但是處理這件事需要一些時間,誰也說不準得花上多久。在這之前,除了使用 Path 或圖形外,我們也可以朝向找尋完全免費授權之免費字型的方向前進,目前筆者能找到的、並確定能使用在 Silverlgiht 的免費中文字型如下:

王漢宗老師:http://briian.com/?p=290
吳老師:ftp://cle.linux.org.tw/pub2/fonts/cwttf/center
文鼎捐贈給自由軟體界的四套字: http://cle.linux.org.tw/fonts/Arphic/
PS:內含兩套簡體字。
雖然王漢宗老師所提供的字型較多且完整,但因為與文鼎有一些法律上的糾紛待處理,所以若你是要用於商業網站上,還是建議使用吳老師或是文鼎所提供的字型,另外!請特別注意一點,Silverlight 的 FontFamily 必須使用英文名稱,以文鼎 PL 中楷來說,FontFamily 必須設定為【AR PL KaitiM Big5】。

當字型、授權不是問題時
OK,現在字型及授權都不是問題了,問題在於你還是得寫下一些 JavaScript 程式碼,使用 Downloader 物件來下載需要的字型,並設定給 TextBlock,這雖然不難,但就是有點繁瑣,基於前次開發 Silverlight DataBindings 技術的經驗,我設計了一組 JavaScript Library 來協助各位更容易的在 Silverlight 上顯示中文。

方便的 JavaScript Library : FontHelper
FontHelper 提供了 Font Bindings 技術,讓你可以直接於 XAM L之 TextBlock 的 Tag 中指定要使用何種字型,如下例:





【DBCS】是 FontHelper 辨識該 TextBlock 是否需要下載字型的關鍵字,【:】號之後的是字型壓縮檔的檔名,此檔案必須放在 Silverlight 網站下,以本例來說是放在網站的根目錄下,【;】後的是修飾字,FontHelper 支援使用者指定一個 default 字型,以本例來說,接下來的 TextBlock 只要以下例方式宣告,就可直接使用 cwkai.zip 的字型。





當呼叫了 FontHelper 物件的 initialize 函式後,其將會搜尋頁面上的 TextBlock 控件,並一一為其下載需要的字型,那麼何時呼叫 initialize 函式呢?在這之前你得先引用 SLFH.js 到你的 Silverlight 網頁中 (此檔可於範例檔中的 SilverlightJSApplication1 或是 SilverlightJSApplication2 等目錄中找到),如下例:

Default.html





SilverlightJSApplication1
















然後在 handleLoad 事件中建立 FontHelper 並呼叫 initialize 函式,如下例:

.xaml.js


handleLoad: function(plugIn, userContext, rootElement)
{
this.plugIn = plugIn;
this.button = rootElement.children.getItem(0);
//建立Font Helper 物件
this.fh = new SilverlightHelper.FontHelper(rootElement);
//呼叫initialize函式,掃描Page 上所有的TextBlock控件,並自動下載字型
this.fh.initialize();;
}


這是靜態字型的使用方式,倘若我想在 JavaScript 中直接使用其它字型呢?FontHelper 提供了 setTextWithFont 函式能幫你達到這個需求。

.xaml.js


//呼叫setTextWithFont來設定TextBlock的字型及文字
//參數:
// setTextWithFont(,<要設定的文字>,<下載的字型>,<字型的FontFamily名稱>)
//
//PS: setTextWithFont不會重覆下載已經下載過的字型!!
this.fh.setTextWithFont(sender.findName("DynamicText"),
"我是動態設置的字","cwfs.zip","cwTeXFangSong");


setTextWithFont 會幫你下載指定的字型到客戶端,並設定指定的文字及 FontFamily,更好的是她會顯示 目前字型的下載進度於畫面上。好了,了解 FontHelper 的大概使用方法後,下面是個實際的例子,你可以在範例壓縮檔中的 SilverlightJSApplication1 目錄中找到這些檔案。

Default.html





SilverlightJSApplication1














Default.html.js


function createSilverlight()
{
var scene = new SilverlightJSApplication1.Scene();
Silverlight.createObjectEx({
source: 'Scene.sxaml',
parentElement: document.getElementById('SilverlightPlugInHost'),
id: 'SilverlightPlugIn',
properties: {
width: '400',
height: '400',
background:'#ffffffff',
isWindowless: 'false',
version: '0.8'
},
events: {
onError: null,
onLoad: Silverlight.createDelegate(scene, scene.handleLoad)
},
context: null
});
}

if (!window.Silverlight)
window.Silverlight = {};

Silverlight.createDelegate = function(instance, method) {
return function() {
return method.apply(instance, arguments);
}
}


Scene.xaml





Storyboard.TargetName="highlightEllipse"
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" />


Storyboard.TargetName="highlightEllipse"
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" />


Storyboard.TargetName="highlightEllipse"
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" />


Storyboard.TargetName="highlightEllipse"
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" />




Width="120" Height="44" Stroke="#46000000">







Canvas.Left="17" Canvas.Top="12" Foreground="#FFEFEFEF" Text="我是中文"
FontFamily="cwTeXKai" FontSize="24" Tag="DBCS:cwkai.zip;default" />
FontSize="26" Text="格式化中文測試" Tag="DBCS:default">


FontHelper 完全支援 TextBlock的Run指令



斜體目前仍無法處理



粗體字也無法處理



Canvas.Top="280"
FontFamily="cwTeXKai"
FontSize="42"
Tag="DBCS:default">
漸層中文字















Fill="#00FFFFFF" Name="highlightEllipse" Canvas.Left="3" Canvas.Top="3"/>




Scene.xml.js


if (!window.SilverlightJSApplication1)
window.SilverlightJSApplication1 = {};


SilverlightJSApplication1.Scene = function()
{
}

SilverlightJSApplication1.Scene.prototype =
{
handleLoad: function(plugIn, userContext, rootElement)
{
this.plugIn = plugIn;
this.button = rootElement.children.getItem(0);

this.button.addEventListener("MouseEnter",
Silverlight.createDelegate(this, this.handleMouseEnter));
this.button.addEventListener("MouseLeftButtonDown",
Silverlight.createDelegate(this, this.handleMouseDown));
this.button.addEventListener("MouseLeftButtonUp",
Silverlight.createDelegate(this, this.handleMouseUp));
this.button.addEventListener("MouseLeave",
Silverlight.createDelegate(this, this.handleMouseLeave));

//建立Font Helper 物件
this.fh = new SilverlightHelper.FontHelper(rootElement);
//呼叫initialize函式,掃描Page 上所有的TextBlock控件,並自動下載字型
this.fh.initialize();;
},

// Sample event handlers
handleMouseEnter: function(sender, eventArgs)
{
// The following code shows how to find an element by name and call a method on it.
var mouseEnterAnimation = sender.findName("mouseEnter");
mouseEnterAnimation.begin();
},

handleMouseDown: function(sender, eventArgs)
{
var mouseDownAnimation = sender.findName("mouseDown");
mouseDownAnimation.begin();
},

handleMouseUp: function(sender, eventArgs)
{
var mouseUpAnimation = sender.findName("mouseUp");
mouseUpAnimation.begin();

// Put clicked logic here
alert("clicked");
//呼叫setTextWithFont來設定TextBlock的字型及文字
//參數:
// setTextWithFont(,<要設定的文字>,<下載的字型>,<字型的FontFamily名稱>)
//
//PS: setTextWithFont不會重覆下載已經下載過的字型!!
this.fh.setTextWithFont(sender.findName("DynamicText"),
"我是動態設置的字","cwfs.zip","cwTeXFangSong");
},

handleMouseLeave: function(sender, eventArgs)
{
var mouseLeaveAnimation = sender.findName("mouseLeave");
mouseLeaveAnimation.begin();
}
}


下圖是執行畫面。



點選按鈕後的畫面。



PS:目前 Silverlight Runtime 1.0 似乎有著一個 Bug,那就是在設定 setFontSource 後, 如粗體、斜體等修飾樣式都將無法使用,即使強制再設定也一樣,此問題不僅發生在中文字型,英文字也一樣。

當字型大小成為問題時
有了 FontHelper 及免費字型的幫忙,相信在你的 Silverlight 網站上使用中文已經不是大問題了,現在的問題是變成是字型檔大小,先讓我們看一下前例於 FireFox 上執行時的流量。



很可怕是吧,這樣一個網頁要價 6.98MB,其實光是字型檔就得要 6.95MB 了,對多數用戶來說,這是無法承受的沉重負擔!

使用 ODTTF
如果字型大小對你或是客戶而言是一個困擾的話 (大部份是),那麼 ODTTF 檔案可能會是解決方案之一,當你的電腦上安裝了 .NET Framework 3.0 時,其順便也為你安裝了 XPS Document Writer 工具,此工具以虛擬印表機的方式呈現,她可以讓你將 Word 檔案輸出成 XPS 檔案,一旦有了這個 XPS 檔案後,我們便可以由其中粹取 ODTTF 檔,這個 ODTTF 檔中包含了該 Word 檔案中所使用的字型,與 TTF 不同,ODTTF 中僅包含用到的字型,所以檔案自然小上許多。以將前例來說,首先我們必須將需要的字型安裝到 Windows 系統中,請以檔案總管開啟 Windows\Fonts 資料夾,由選單之檔案|安裝新字型來安裝所需要的字型:





接著準備一個 Word 檔案,內容如下,請注意!字體要選擇所需要的。





完成後選擇列印。



點選確定後選擇存檔位置。



待輸出完成後,請該檔案之副檔名由 .xps 改成 .zip,解壓後可於其中找到 .ODTTF 的檔案。



將這三個檔案再壓縮成一個 zip 檔案,將檔名取為 partialFonts.zip,放到 SilverlightJSApplication1 的目錄下,然後修改 Sence.xaml 及 Sence.xaml.js 如下。

Sence.xaml





Storyboard.TargetName="highlightEllipse"
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" />


Storyboard.TargetName="highlightEllipse"
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" />


Storyboard.TargetName="highlightEllipse"
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" />


Storyboard.TargetName="highlightEllipse"
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" />




Height="44" Stroke="#46000000">







Canvas.Top="12" Foreground="#FFEFEFEF" Text="我是中文"
FontFamily="cwTeXKai" FontSize="24" Tag="DBCS:partialFonts.zip;default" />
FontSize="26" Text="格式化中文測試" Tag="DBCS:default">


FontHelper 完全支援 TextBlock的Run指令



斜體目前仍無法處理



粗體字也無法處理



Canvas.Top="280"
FontFamily="cwTeXKai"
FontSize="42"
Tag="DBCS:default">
漸層中文字















Fill="#00FFFFFF" Name="highlightEllipse" Canvas.Left="3" Canvas.Top="3"/>





Sence.xaml.js


if (!window.SilverlightJSApplication1)
window.SilverlightJSApplication1 = {};


SilverlightJSApplication1.Scene = function()
{
}

SilverlightJSApplication1.Scene.prototype =
{
handleLoad: function(plugIn, userContext, rootElement)
{
this.plugIn = plugIn;
this.button = rootElement.children.getItem(0);

this.button.addEventListener("MouseEnter",
Silverlight.createDelegate(this, this.handleMouseEnter));
this.button.addEventListener("MouseLeftButtonDown",
Silverlight.createDelegate(this, this.handleMouseDown));
this.button.addEventListener("MouseLeftButtonUp",
Silverlight.createDelegate(this, this.handleMouseUp));
this.button.addEventListener("MouseLeave",
Silverlight.createDelegate(this, this.handleMouseLeave));

//建立Font Helper 物件
this.fh = new SilverlightHelper.FontHelper(rootElement);
//呼叫initialize函式,掃描Page 上所有的TextBlock控件,並自動下載字型
this.fh.initialize();;
},

// Sample event handlers
handleMouseEnter: function(sender, eventArgs)
{
// The following code shows how to find an element by name and call a method on it.
var mouseEnterAnimation = sender.findName("mouseEnter");
mouseEnterAnimation.begin();
},

handleMouseDown: function(sender, eventArgs)
{
var mouseDownAnimation = sender.findName("mouseDown");
mouseDownAnimation.begin();
},

handleMouseUp: function(sender, eventArgs)
{
var mouseUpAnimation = sender.findName("mouseUp");
mouseUpAnimation.begin();

// Put clicked logic here
alert("clicked");
//呼叫setTextWithFont來設定TextBlock的字型及文字
//參數:
// setTextWithFont(,<要設定的文字>,<下載的字型>,<字型的FontFamily名稱>)
//
//PS: setTextWithFont不會重覆下載已經下載過的字型!!
//this.fh.setTextWithFont(sender.findName("DynamicText"),
//"我是動態設置的字","cwfs.zip","cwTeXFangSong");
this.fh.setTextWithFont(sender.findName("DynamicText"),
"我是動態設置的字","partialFonts.zip","cwTeXFangSong");
},

handleMouseLeave: function(sender, eventArgs)
{
var mouseLeaveAnimation = sender.findName("mouseLeave");
mouseLeaveAnimation.begin();
}
}



完成後執行,使用 FireFox 的流量分析如下所示。



只需 67KB,很戲劇化的結果是吧。

字型部份下載:XPS Font Service
使用 ODTTF 的優點是字型檔較小,缺點則是必須仰賴 Word 及 XPS Document Writer 來製作 ODTTF 檔案,在需要由資料庫或是與使用者互動來動態顯示中文字的應用上,這種解法就完全不適用了!當然,你可以事先準備較多的中文字,但這畢竟不是 100% 完整的解法!!那麼到頭來還是得下載所有字型了嗎?不見得!我們能用WPF將字轉成 Path,當然也能如法泡製將字轉成 XPS,然後粹取出 ODTTF 後壓縮回傳到客戶端,當然!前題得先在網站伺服器上安裝 .NET Framework 3.0,下面列出 Font Services 及使用她的 GetFontsXPS.aspx、及 ZIP 壓縮解壓縮部份 (此處使用 SharpZipLib 這個免費的 Zip 物件庫,可以在 http://www.icsharpcode.net/OpenSource/SharpZipLib/ 取得) 的原始碼,你可以在範例壓縮檔的 SilverlightJSApplication2 中找到她們。

FontServces.cs


using System;
using System.ComponentModel;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
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.Windows;
using System.Globalization;
using System.Windows.Media;
using System.IO.Packaging;
using System.IO;
using System.Windows.Xps;
using System.Printing;
using System.Windows.Xps.Packaging;
using System.Text;
using System.Reflection;
using System.Security.Permissions;

public class FontService
{
private static Dictionary _fontMapping = new Dictionary();

static FontService()
{
//王老師的字型(由於與文鼎有些爭議未決,建議多使用吳老師的)
_fontMapping.Add("HanWangMingLight", "王漢宗細明體繁");
_fontMapping.Add("HanWangMingMedium", "王漢宗中明體繁");
_fontMapping.Add("HanWang WeiBeiMedium-Gb5", "王漢宗中魏碑簡");
_fontMapping.Add("HanWang FangSongMedium-Gb5", "王漢宗中仿宋簡");
//吳老師的字型
_fontMapping.Add("cwTeXHeiBold", "cwTeXHeiBold");
_fontMapping.Add("cwTeXFangSong", "cwTeXFangSong");
_fontMapping.Add("cwTeXKai", "cwTeXKai");
_fontMapping.Add("cwTeXYen", "cwTeXYen");
_fontMapping.Add("cwTeXMing", "cwTeXMing");
}

//create xps.
private DrawingVisual CreateDrawingVisualText(string formattedText,
string fontName, CultureInfo ci)
{
// Create an instance of a DrawingVisual.
DrawingVisual drawingVisual = new DrawingVisual();

// Retrieve the DrawingContext from the DrawingVisual.
DrawingContext drawingContext = drawingVisual.RenderOpen();

// Draw a formatted text string into the DrawingContext.
drawingContext.DrawText(
new FormattedText(formattedText,
ci,
FlowDirection.LeftToRight,
new Typeface(fontName),
12, Brushes.Black),
new Point(200, 116));

// Close the DrawingContext to persist changes to the DrawingVisual.
drawingContext.Close();
return drawingVisual;
}


private void VisualToXps(string fileName, string formattedText,
string fontName, CultureInfo ci)
{

Package package = Package.Open(fileName, FileMode.Create);
{
XpsDocument doc = new XpsDocument(package, CompressionOption.SuperFast);
{

XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);
writer.Write(CreateDrawingVisualText(formattedText, fontName, ci));
}
doc.Close();
}
package.Close();
}


private FileStream BuildFontFont(string formattedText, string fontName, CultureInfo ci)
{
string key = Guid.NewGuid().ToString();
if (!Directory.Exists(HttpRuntime.AppDomainAppPath + "App_Data\\TempFonts"))
Directory.CreateDirectory(HttpRuntime.AppDomainAppPath + "App_Data\\TempFonts");
string basePath = HttpRuntime.AppDomainAppPath + "App_Data\\TempFonts\\";
VisualToXps(basePath + "\\" + key + ".xps", formattedText, fontName, ci);
Compression.UnZipClass unZip = new Compression.UnZipClass();
string fileName = unZip.UnZip(basePath + "\\" + key + ".xps", basePath);
File.Delete(basePath + "\\" + key + ".xps");
Compression.ZipClass Zip = new Compression.ZipClass();
Zip.ZipFile(fileName, HttpRuntime.AppDomainAppPath + "CachedFonts\\" +
key + ".zip", 8, 8192);
File.Delete(fileName);
return new FileStream(HttpRuntime.AppDomainAppPath + "CachedFonts\\" +
key + ".zip", FileMode.Open, FileAccess.Read);
}

private void DeleteOutDateFonts()
{
foreach (string item in Directory.GetFiles(
HttpRuntime.AppDomainAppPath + "CachedFonts\\"))
{
DateTime dt = File.GetCreationTime(item);
TimeSpan ts = DateTime.Now - dt;
if (ts.Hours > 2)
File.Delete(item);
}
}

public FontService(Page page)
{
page.Load += new EventHandler(page_Load);
}

void page_Load(object sender, EventArgs e)
{
Page page = (Page)sender;
if (!String.IsNullOrEmpty(page.Request.QueryString["FontName"]))
{
DeleteOutDateFonts();
string fontName = page.Request.QueryString["FontName"];
string texts = page.Server.UrlDecode(Encoding.Default.GetString(
Convert.FromBase64String(page.Request.QueryString["Data"])));
if (_fontMapping.ContainsKey(fontName))
fontName = _fontMapping[fontName];
FileStream fs = BuildFontFont(texts, fontName,
CultureInfo.GetCultureInfo("zh-TW"));
fs.Close();
page.Response.Clear();
page.Response.Write("CachedFonts/" + Path.GetFileName(fs.Name));
page.Response.End();
}
}
}



DeCompress.cs


using System;
using System.Text;
using System.Collections;
using System.IO;
using System.Diagnostics;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web;

using ICSharpCode.SharpZipLib.BZip2;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Checksums;


namespace Compression
{
public class UnZipClass
{
public string UnZip(string fileName,string basePath)
{
string name = string.Empty;
using (FileStream inputStream = new FileStream(fileName,
FileMode.Open, FileAccess.Read))
{
ZipInputStream s = new ZipInputStream(inputStream);

ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(theEntry.Name);
if (directoryName == "Resources")
{
if (!Directory.Exists(
HttpRuntime.AppDomainAppPath + "App_Data\\TempFonts"))
Directory.CreateDirectory(
HttpRuntime.AppDomainAppPath + "App_Data\\TempFonts");
FileStream fs = File.Create(basePath+"\\"+
Path.GetFileName(theEntry.Name));
name = fs.Name;
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
fs.Write(data, 0, size);
else
break;
}
fs.Close();
break;
}
}
s.Close();
}
return name;
}
}


public class ZipClass
{
public void ZipFile(string FileToZip, string ZipedFile,
int CompressionLevel, int BlockSize)
{
FastZip fz = new FastZip();
fz.CreateZip(ZipedFile, Path.GetDirectoryName(FileToZip), false,
Path.GetFileName(FileToZip));
}
}
}



GetFontsXPS.aspx.cs


using System;
using System.ComponentModel;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
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.Windows;
using System.Globalization;
using System.Windows.Media;
using System.IO.Packaging;
using System.IO;
using System.Windows.Xps;
using System.Printing;
using System.Windows.Xps.Packaging;
using System.Text;
using System.Reflection;
using System.Security.Permissions;



public partial class GetFontsXPS : System.Web.UI.Page
{
private FontService _fontServices = null;

public GetFontsXPS()
{
_fontServices = new FontService(this);
}
}



Font Services 的設計是希望透過 ASP.NET 接收客戶端所傳上來的 FontName 及 Data 參數來動態產生 XPS,然後粹取出 ODTTF 後再壓縮後回傳給客戶端,基於必須由 JavaScript 將中文字送上來的緣故,Data 參數必須在 JavaScript 端轉成 Base64 後才能送上來解碼,FontHelper 提供了這些功能。

FontHelper 於 XPS Font Service
FontHelper 支援使用 XPS Font Service,SilverlightJSApplication2 就是使用 XPS Font Service 的例子。

Scene.xaml





Storyboard.TargetName="highlightEllipse"
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" />


Storyboard.TargetName="highlightEllipse"
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" />


Storyboard.TargetName="highlightEllipse"
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" />


Storyboard.TargetName="highlightEllipse"
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" />




Width="120" Height="44" Stroke="#46000000">







Canvas.Top="12" Foreground="#FFEFEFEF" Text="我是中文"
FontFamily="cwTeXKai" FontSize="24" Tag="XPS:GetFontsXPS.aspx?FontName=cwTeXKai" />
Text="格式化中文測試" Tag="XPS:GetFontsXPS.aspx?FontName=cwTeXKai">

FontHelper 完全支援 TextBlock的Run指令

斜體目前仍無法處理

粗體字也無法處理


Canvas.Top="280"
FontFamily="cwTeXKai"
FontSize="42"
Tag="XPS:GetFontsXPS.aspx?FontName=cwTeXKai">
漸層中文字





















Secne.xaml.js


if (!window.SilverlightJSApplication1)
window.SilverlightJSApplication1 = {};


SilverlightJSApplication1.Scene = function()
{
}

SilverlightJSApplication1.Scene.prototype =
{
handleLoad: function(plugIn, userContext, rootElement)
{
this.plugIn = plugIn;
this.rootElement = rootElement;
this.button = rootElement.children.getItem(0);

this.button.addEventListener("MouseEnter",
Silverlight.createDelegate(this, this.handleMouseEnter));
this.button.addEventListener("MouseLeftButtonDown",
Silverlight.createDelegate(this, this.handleMouseDown));
this.button.addEventListener("MouseLeftButtonUp",
Silverlight.createDelegate(this, this.handleMouseUp));
this.button.addEventListener("MouseLeave",
Silverlight.createDelegate(this, this.handleMouseLeave));
var fh = new SilverlightHelper.FontHelper(rootElement);
fh.initialize();
},

// Sample event handlers
handleMouseEnter: function(sender, eventArgs)
{
// The following code shows how to find an element by name and call a method on it.
var mouseEnterAnimation = sender.findName("mouseEnter");
mouseEnterAnimation.begin();
},

handleMouseDown: function(sender, eventArgs)
{
var mouseDownAnimation = sender.findName("mouseDown");
mouseDownAnimation.begin();
var fh = new SilverlightHelper.FontHelper(this.rootElement);
var input = document.getElementById("DyanmicInput");
if(input && input.value && input.value != '')
fh.setTextWithXPS(sender.findName("DynamicText"),input.value,
"GetFontsXPS.aspx?FontName=cwTeXFangSong","cwTeXFangSong");
else
fh.setTextWithXPS(sender.findName("DynamicText"),
"我是動態由JavaScript設定的","GetFontsXPS.aspx?FontName=cwTeXFangSong","cwTeXFangSong");
},

handleMouseUp: function(sender, eventArgs)
{
var mouseUpAnimation = sender.findName("mouseUp");
mouseUpAnimation.begin();

// Put clicked logic here
alert("clicked");
},

handleMouseLeave: function(sender, eventArgs)
{
var mouseLeaveAnimation = sender.findName("mouseLeave");
mouseLeaveAnimation.begin();
}
}



除了靜態文字外,FontHelper 提供了相對於 setTextWithFont 的 setTextWithXPS 函式可供指定動態文字用,如下所示。


handleMouseDown: function(sender, eventArgs)
{
var mouseDownAnimation = sender.findName("mouseDown");
mouseDownAnimation.begin();
var fh = new SilverlightHelper.FontHelper(this.rootElement);
var input = document.getElementById("DyanmicInput");
if(input && input.value && input.value != '')
fh.setTextWithXPS(sender.findName("DynamicText"),input.value,
"GetFontsXPS.aspx?FontName=cwTeXFangSong","cwTeXFangSong");
else
fh.setTextWithXPS(sender.findName("DynamicText"),
"我是動態由JavaScript設定的",
"GetFontsXPS.aspx?FontName=cwTeXFangSong","cwTeXFangSong");
}



下圖是執行範例。



下圖是輸入文字後,再點選 (我是中文) 按鈕後的執行畫面。



PS:請特別注意,你必須將需要的中文字型安裝到 Windows 中方能使用 XPS Font Services。

就這樣!中文不再是 Silverlight 的致命傷!
就這樣,困擾我們多時的 Silverlight 顯示中文問題,在 XPS Font Services 及免費中文字型及 Font Helper Library 的協助下得以完全解決,在此特別感謝吳老師所提供的免費字型!!未來希望微軟也能開放字型授權,屆時我們會有更多的字型可選擇。

Developer Notes
當你使用 Font Binding Helper 時,於下載字型時發生 Download/Network Error,請檢查 TextBlock 之 TAG 設定值,所要求的檔案可能不在目錄中,亦或是要求的字型未安裝至 Windows 系統中 (Use XPS)。
範例檔中的 Font Binding Helper 及 Font Services 最新版本已支援大量字處理,當要顯示的字大於 100 個時,Font Binding Helper 及 Font Servcies 會自動分批下載並整合 (Downloader 在處理長度過長的 URL 會出現錯誤)。
受限於 Cross-Domain 的設計,Font Services (GetFontsXPS.aspx、FontServcies.cs) 必須與 Silverlight 網頁放在同一網站中。
Font Servcies 會將字型檔案產生於 App_Data\TempFonts 及 CachedFonts 目錄中,因此若你想將 Silverlight 網站安裝到 IIS 中,請預先建立這幾個目錄,並設定目錄存取權限 (以 Windows 2003 來說,必須新增 IIS_WPG 為完全授權使用者)。
吳老師的兩個字型 (楷書與仿宋) 位於範例檔中的 SilverlightJSApplication1 目錄中,以 .zip 方式壓縮,若你想使用 XPS Font Service,請自行解壓後安裝到 Windows 字型中。
本文列出之範例程式碼僅是參考,完整請參照範例檔,若有更新,文章將不另行更新。
因 Visual Studio 2005 之 Silverlight XAML Designer 目前與中文有不相容的問題,若你開啟專案後發現 Scene.xaml 中的中文變成亂碼,那麼請由目錄下我所準備的備份檔 backup_xaml.txt 複製回來。
範例檔下載:http://code6421.myweb.hinet.net /SLFH_Samples.zip (19MB)