0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ListBox(ListView)の複数選択をMVVMで判断する

Posted at

自分向けのメモ。

WPF アプリの ListBox(ListView) を複数選択対応にする場合。XAMLとVMだけで完結する

<Window><!--名前空間などは省略-->
  <Window.DataContext>
    <ViewModel />
  </Window.DataContext>
  <ListBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}"
           SelectionMode="Extended">
           <!--SelectionMode=Multipleでもよい, Singleだと単一選択になる-->
    <ListBox.ItemContainerStyle>
      <Style TargetType="ListBoxItem">
        <Setter Property="IsSelected" Value="{Binding IsSelected}" />
      </Style>
    </ListBox.ItemContainerStyle>
  </ListBox>
</Window>
class Item : ObservableObject
{
  [ObservableProperty]
  bool isSelected;

  // 選択状態が変更された場合に何かしたい場合はこれをハンドリングすればよい
  //partial void OnIsSelectedChanged( bool value )
  //{
  //}
}
class ViewModel : ObservableObject
{
  // リストボックスのItemsSource にバインドする
  public ObservableCollection<Item> Items { get; set; }

  // 単一選択の場合の選択アイテム(複数選択した場合は来ない)
  [ObservableProperty]
  Item selectedItem;

  void SelectWork()
  {
   foreach( var item in Items.Where( i => i.IsSelected ) )
   {
     // 選択アイテムに対して何かやる
   }
  }
}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?