作者:馬甯
示例代碼下載下傳見附件。
寫這篇BLOG完全是因為看了MSDN上的這篇文章:
http://msdn.microsoft.com/en-us/magazine/ff960707.aspx
Windows Phone 7的開發工具不支援動态語言,是以IronRuby支援Windows Phone 7就顯得格外重要了。剛看這篇文章的時候,還鬧了個笑話,看了一遍代碼,一句都不認識,心想難道語言換到.NET上,變化怎麼這麼大?仔細一看,原來是Ruby,而不是Python ^_^,小蟒蛇這次落後了。以前用Python寫過自動化測試腳本,沒接觸過Ruby,是以,把Ruby看成Python了。
不支援動态語言,一直是Windows Mobile程式設計的痛,這次終于有搞頭了。終于可以動态改變程式的邏輯了,光這一點就給我們提供了無限的想象空間。Windows Phone上的F#也快了吧?^_^
言歸正傳,這次我完全是照葫蘆畫瓢,隻是将自己嘗試中的一些關鍵點寫出來,讓大家少走彎路。更多資訊大家可以參考Shay Friedman的BLOG:http://ironshay.com/
首先,我們要下載下傳IronRuby for Windows Phone版本(.NET 3.5):
http://ironruby.codeplex.com/releases/view/43540#DownloadId=133276
然後,在Visual Studio 2010中建立一個Silverlight for Windows Phone 7的工程,工程名叫做“IronRubyWP7”,然後選擇“Project”菜單的“Add Reference”選項,在彈出的對話框中,選擇“Browse”标簽,我們可以找到解壓後的IronRuby目錄,将\silverlight\bin中的DLL檔案加入到工程中來:

接下來,我們在工程中添加一個文本檔案,在Solution Explorer中選中IronRubyWP7,右鍵,“Add”-“New Item”,在對話框中選擇“Text File”,将檔案名改為“MainPage.rb”。
選中MainPage.rb檔案,在屬性中将“Build Action”設定為“Embedded Resource”。
- # Include namespaces for ease of use
- include System::Windows::Media
- include System::Windows::Controls
- # Set the titles
- Phone.find_name("ApplicationTitle").text = "aawolf.cnblogs.com"
- Phone.find_name("PageTitle").text = "IronRuby& WP7"
- # Create a new text block
- textBlock = TextBlock.new
- textBlock.text = "IronRuby is running on Windows Phone 7!"
- textBlock.foreground = SolidColorBrush.new(Colors.Green)
- textBlock.font_size = 48
- textBlock.text_wrapping = System::Windows::TextWrapping.Wrap
- # Add the text block to the page
- Phone.find_name("ContentPanel").children.add(textBlock)
請注意,我修改了最後一行的容器控件名稱,原示例中的名稱是“ContentGrid”,但是Silverlight for Windows Phone向導預設建立的XAML檔案中容器類名稱是“ContentPanel”。這裡會引起一個運作期錯誤,因為IronRuby不能Debug,是以第一次調試起來比較痛苦。
接下來,我們要打開MainPage.xaml.cs檔案,将IronRuby初始化代碼,加入到MainPage類的構造函數中:
- public partial class MainPage : PhoneApplicationPage
- {
- // Constructor
- public MainPage()
- {
- InitializeComponent();
- // Allow both portrait and landscape orientations
- SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;
- // Create an IronRuby engine and prevent compilation
- ScriptEngine engine = Ruby.CreateEngine();
- // Load the System.Windows.Media assembly to the IronRuby context
- engine.Runtime.LoadAssembly(typeof(Color).Assembly);
- // Add a global constant named Phone, which will allow access to this class
- engine.Runtime.Globals.SetVariable("Phone", this);
- // Read the IronRuby code
- Assembly execAssembly = Assembly.GetExecutingAssembly();
- Stream codeFile =
- execAssembly.GetManifestResourceStream("IronRubyWP7.MainPage.rb");
- string code = new StreamReader(codeFile).ReadToEnd();
- // Execute the IronRuby code
- engine.Execute(code);
- }
- }
請大家注意InitializeComponent方法的位置,在初始化IronRuby運作時之前,一定要先完成控件初始化的工作,這是我血和淚的教訓。另外一個需要注意的地方,就是讀取Ruby檔案的路徑。我們似乎也可以通過HttpRequest擷取一個Stream是吧?笑而不語 ^_^
最後運作的效果是這樣子的,整個開發過程曆時兩小時:
相關資源
馬甯的Windows Phone 7開發教程(1)——Windows Phone開發工具初體驗