Silverlight 4におけるアプリケーション要件への挑戦 – Drag & Drop

Drag & Drop

皆様、こんにちは。先程の投稿に次いで、今度はDrag & Dropです。

Silverlight 3の時にも、ブラウザー間でのオブジェクトのドラッグ&ドロップは可能でした。Silverlight 4 では、ローカルシステムから Silverlight アプリケーションへのファイルのDrag & Dropをサポートしました。これによりデスクトップアプリケーションにおける典型的な操作が可能です。

ここでは、まずは、CodeProjectに紹介されているサンプルのご紹介をしておきます。

ツールキットへの参照設定

これはSilverlightの ListBox コントロールの中でのドラッグ&ドロップの実装サンプルであり、2つのListBox間でのドラッグ&ドロップの操作の実装も行われています(これを実装するには、Silverlight 4 Toolkit がインストールされていることが必要です)。

最初のポイントとしては、Silverlight Toolkitへの参照設定及びxmlns:toolkit:toolkit として名前を参照できるようにすることが必要です。

まずVisual Studio 2010で適当な名前でSilverlightのプロジェクトを作成します。そしてMainPage.xamlを開き、編集していきます。

 xmlns:toolKit=
"clr-namespace:System.Windows.Controls; 
  assembly=System.Windows.Controls.Toolkit"

次に、ListBoxDragDropTargetGridの中に追加し、プロパティウィンドウで、属性の“AllowDrop” をTrueにしておく必要があります。

ListBoxDragDropTargetの追加とAllowDrop属性の変更

 <toolKit:ListBoxDragDropTarget AllowDrop="True">
</toolKit:ListBoxDragDropTarget>

そして、各々ListBoxDragDropTargetに囲まれた2つのListBoxを追加し、配置します。

ListBoxの追加と配置

 <StackPanel Orientation="Horizontal" Margin="10" Grid.Row="1">
    <toolKit:ListBoxDragDropTarget AllowDrop="True">
        <ListBox x:Name="customerListBoxMain" 
 Height="200" Width="200"
    DisplayMemberPath="Name">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Vertical"/>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>
    </toolKit:ListBoxDragDropTarget>
    <TextBlock Width="20" />
    <toolKit:ListBoxDragDropTarget AllowDrop="True">
        <ListBox 
  Height="200" Width="200"
    DisplayMemberPath="Name">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Vertical"/>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>
    </toolKit:ListBoxDragDropTarget>
</StackPanel>

image

ListBoxDragDropTargetのプロパティを見ると、このようにAllowDropにチェックが入っているはずです。

XAMLのUIを作り終えたら、データを一方のListBoxから取得して、他方のListBoxにセットするという処理を、分離コードに書きます。

Drag & Drop の分離コード側の処理

 public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();

        customerListBoxMain.ItemsSource = 
       PersonDataProvider.GetData();
    }
}

実行イメージはこのようになります。左右2つのListBox間でも、どちらか1つのListBoxの中でも、Drag & Dropが可能になっていることがお分かり頂けるでしょう。

image

Drag & Drop ListBox Demoの実行イメージ

参照 : 本アプリケーションの詳細はこちらをご参照ください。

How to Drag and Drop between ListBox using Silverlight 4 Toolkit?

https://www.codeproject.com/KB/silverlight/SL4DragDropListBox.aspx

なお、Silverlight Training Kitのサンプルには、典型的な”ファイルからのDrag & Drop” を実装したものがあります。これは前々回のエントリ(Copy & Paste )でご紹介したこちらです。

image5

RichNotePadの実行イメージ

場所は、普通にSilverlight 4 Training Kitをインストールした場合には、下記のフォルダになります。

C:\Silverlight4\Labs\RichTextBox\Source\Ex02\End

インストール済みの方は是非、こちらを参照してください。

以上です。いかがでしょうか?次回は、右クリック、印刷機能等、順に取り上げます。

鈴木 章太郎