LoginSignup
11
12

More than 5 years have passed since last update.

WPF ListBoxのSeletedItemsにデータバインディングする。

Posted at

久しぶりにWPFのListBoxを使ったのですよ。
そうしたら、複数選択しているアイテムをデータバインディングできない。
単数の選択したものは、できるのですが、複数がない。

MVVM的に作れないじゃないですかー。

そういえば、Mouse Event Commands for MVVM
で、どのコントロールのマウスイベントもデータバインディングさせるというとても便利技があったので、これの応用でやってみた。

filename

public class ListBoxBehaviour
    {  
        public static readonly DependencyProperty SeletedItemsProperty =
            DependencyProperty.RegisterAttached("SeletedItems", typeof(IList), typeof(ListBoxBehaviour), new PropertyMetadata(new PropertyChangedCallback(SeletedItemsChanged)));
        static void SeletedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ListBox element = (ListBox)d;
            element.SelectionChanged += Element_SelectionChanged;
        }

        static void Element_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox element = (ListBox)sender;
            element.SetValue(SeletedItemsProperty, element.SelectedItems);            
        }

        public static void SetSeletedItems(UIElement element, IList value)
        {
            element.SetValue(SeletedItemsProperty, value);
        }

        public static IList GetSeletedItems(UIElement element)
        {
            return (IList)element.GetValue(SeletedItemsProperty);
        }
    }

これをWPFで参照するようにして。

filename
 <ListBox MyControl:ListBoxBehaviour.SeletedItems="{Binding SelectedQuestion,Mode=TwoWay}" >

こういう感じに書くて、VM側は、IListで受けるようにすると、VM側で選択されているアイテムの取得ができる。

はじめから用意していてよ・・・。

ネタ元のマウスイベントをデータバインディングさせる技もそうですが、こういう感じにやれば、標準ではできない、イベントなりプロパティを強引にデータバインディングできますね。

11
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12