Silverlight でも Command を使用する

オープンソースの SLExtensions というライブラリを使用すれば、Silverlight でも Command が使用可能になります。

Command 関連のクラスは SLExtensions.dll 内の SLExtensions.Input 名前空間の中に用意されています。

Page.xaml

<UserControl x:Class="CommandSample.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:input="clr-namespace:SLExtensions.Input;assembly=SLExtensions"
    Width="400" Height="300">
    <StackPanel x:Name="LayoutRoot" Background="White">
        <Button Content="メッセージ表示!" input:CommandService.Command="ShowMessage"/>
        <TextBlock Text="メッセージ表示!" input:CommandService.Command="ShowMessage"/>
    </StackPanel>
</UserControl>

CommandService クラスの Command 添付プロパティで、Button や TextBlock がクリックされたときに実行する Command を指定しています。

Page.xaml.cs

using System.Windows;
using System.Windows.Controls;
using SLExtensions.Input;

namespace CommandSample
{
    public partial class Page : UserControl
    {
        public Page()
        {
            // コマンドを登録する
            var command = new Command("ShowMessage");
            command.Executed += (sender, e) =>
            {
                string message = string.Format(
                    "{0} に設定したコマンドを実行したよ!",
                    e.Source.GetType());
                MessageBox.Show(message);
            };

            InitializeComponent();
        }
    }
}

生成した Command インスタンスはローカル変数 command に格納しているだけで、メンバ変数として保持していません。しかし ShowMessage という名前の Command は Command.CommandCache に保存されています。もう一度 ShowMessage という名前で Command を生成しようとすると例外が発生するので注意して下さい。

実行画面

Button をクリックしたときがこちら。
f:id:griefworker:20090306165940p:image

TextBlock をクリックしたときがこちら。
f:id:griefworker:20090306165954p:image

何がクリックされて実行した Command なのかを MessageBox で表示しています。ちゃんと動いてますね。