12月 12

従来、ドラッグ&ドロップでListBoxのアイテムの並び順を変えるのは、少々めんどうでしたが、Silverlight3 の対応により、とても簡単に行えるようになったようです。

image

そもそも、WPF/Silverlight の ListBox は、単純な文字列から複雑なコントロール群まで、なんでも格納できるというパワフルなものですが、ここに数行のコードを追加するだけで、ドラッグ&ドロップなんかも簡単に実装できるんですね。

ポイント

  1. 格納したいオブジェクト群を 「ObservableCollection」 というリストに格納します。
    • ObservableCollection<StackPanel> commandList = new ObservableCollection<StackPanel>();
  2. その ObservableCollection を ListBox.ItemSource にセット。
    • this.CommandListBox.ItemsSource = this.commandList;
  3. XAMLで下記の太字部分を追加してやります。

<Grid x:Name="LayoutRoot">
 
<controlsToolkit:ListBoxDragDropTarget msWindows:DragDrop.AllowDrop="True">
      <ListBox x:Name="CommandList">
          <ListBox.ItemsPanel>
              <ItemsPanelTemplate>
                  <StackPanel Orientation="Vertical" />
              </ItemsPanelTemplate>
          </ListBox.ItemsPanel>
      </ListBox>
 
</controlsToolkit:ListBoxDragDropTarget>
</Grid>

ネタ元

http://www.xdevsoftware.com/blog/post/Reorderlist-with-Silverlight-3-Drag-and-Drop-Listbox-.aspx

余談になりますが、上記の XAML では <ListBox.ItemsPanel> として <StackPanel> を定義していますが、この StackPanel の Vertical を Horizontal にするだけで、横方向の ListBox も作れてしまいます。

このあたりの柔軟さが、XAML の魅力ですね。

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes