IronPython で Silverlight 2.0 - ボタン表示

前回 id:fits:20080310 のサンプルに手を加えて、ボタンを表示する簡単なサンプルを作ってみた。使用したのは前回と同様に Silverlight SDK 2.0 Beta1。

前回との違いは以下のような点。

  • app ディレクトリに AppManifest.xaml ファイルを用意(前回は chiron.exe が自動的に生成)
  • app ディレクトリに使用するアセンブリファイル(Button クラスを使うための System.Windows.Controls.dll 等)を配置

ただし、上記のような手作業が本当に必要なのかという点に関して確証は持てていない。もっと簡単な方法があるのかもしれないが、少なくとも chiron.exe を通常実行しただけでは System.Windows.Controls.dll 等を使用できるようにならなかった。

なお、ディレクトリ構成や index.html は基本的に id:fits:20080310 と同様のものを使用。

XAML ファイル作成

XAML ファイルでは Button 要素を使ってボタンを定義。

app.xaml
<UserControl xmlns="http://schemas.microsoft.com/client/2007"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   x:Class="System.Windows.Controls.UserControl"
   x:Name="Page">

    <StackPanel Orientation="Vertical">
        <Button x:Name="testButton" Content="ボタン" />
        <TextBlock x:Name="testBlock" Text="てすと" />
    </StackPanel>
</UserControl>

IronPython スクリプト作成

IronPython 側でボタンの Click イベント発生時にアラートを表示する処理を実装。
アラート表示は System.Windows.Browser.HtmlWindow クラスに Alert メソッドが用意されていたため、それを使用する事にした。
なお、HtmlWindow のインスタンスは HtmlPage クラスの Window プロパティで取得。

app.py
from System.Windows import Application
from System.Windows.Controls import UserControl
from System.Windows.Browser import HtmlPage

def onClickButton(sender, args):
	HtmlPage.Window.Alert("ボタンクリック");

scene = Application.Current.LoadRootVisual(UserControl(), 'app.xaml')
scene.testButton.Click += onClickButton

AppManifest.xml 作成

chiron.exe が自動的に生成する AppManifest.xml をベースに、Button クラスのための System.Windows.Controls.dll のエントリを追加。

AppManifest.xml
<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment" 
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  EntryPointAssembly="Microsoft.Scripting.Silverlight" 
  EntryPointType="Microsoft.Scripting.Silverlight.DynamicApplication" 
  RuntimeVersion="2.0.30226.2">
  <Deployment.Parts>
    <!-- Add additional assemblies here -->
    <AssemblyPart x:Name="System.Windows.Controls" Source="System.Windows.Controls.dll" />

    <AssemblyPart Name="Microsoft.Scripting.Silverlight" Source="Microsoft.Scripting.Silverlight.dll" />
    <AssemblyPart Source="Microsoft.Scripting.dll" />
    <AssemblyPart Source="IronPython.dll" />
    <AssemblyPart Source="IronPython.Modules.dll" />
  </Deployment.Parts>
</Deployment>

ビルドと実行

app ディレクトリに以下のファイルをコピー。

  • System.Windows.Controls.dll

なお、System.Windows.Controls.dll は "C:\Program Files\Microsoft SDKs\Silverlight\v2.0\Libraries\Client" からコピーした。

chiron.exe を実行して app.xap ファイルを生成。

>chiron.exe /directory:app /zipdlr:app.xap

index.html を Web ブラウザで表示し、ボタンを押下すると Web ブラウザのアラートが表示される。