[C# WPF] コードビハインドからListBoxの要素を複数選択する
2019年4月18日
たまに使うと忘れているので書いておきます。
何も考えずにListBox.SelectedItemを更新してしまうと既に選択してあった項目の選択状態も解除されてしまいます。
もくじ
スポンサーリンク
サンプルコード
例えば、XAMLで以下のようにListBoxを宣言しているとします。
<ListBox x:Name="xListBox" SelectionMode="Multiple"> <ListBoxItem Content="aaa" IsSelected="True"/> <ListBoxItem Content="bbb"/> <ListBoxItem Content="ccc"/> <ListBoxItem Content="ddd"/> <ListBoxItem Content="eee"/> </ListBox>
この場合、コードビハインドでは以下の方法で複数選択ができます。
// その1 xListBox.SelectedItems.Add(xListBox.Items[2]); // その2 var item = xListBox.Items[3] as ListBoxItem; item.IsSelected = true; // その3 // ListBoxの要素がDependencyObjectの場合にはこちらも使えます. // ListBoxItemはDependencyObjectです. Selector.SetIsSelected((DependencyObject)xListBox.Items[4], true);
また、以下のようにListBox.ItemsSourceにDependencyObject以外のオブジェクトのリストを設定している場合には、上記の「その1」の方法で設定します。
xListBox.ItemsSource = new List<string> { "aaa", "bbb", "ccc" }; // OK xListBox.SelectedItems.Add(xListBox.Items[0]); // NG (自動的にListBoxItemにはならないので、asはnullを返す) var item = xListBox.Items[1] as ListBoxItem; // NG (stringはDependencyObjectではないので、castに失敗する) Selector.SetIsSelected((DependencyObject)xListBox.Items[2], true);
おしまい。
スポンサーリンク
関連記事

[C# WPF] StreamGeometryのLineTo()の長さ制限
WPFでStreamGeometryを使って直線を描画していると、ときどき直線が ...

[C# WPF] 描画範囲を制限する
描画時にクリップする方法のまとめです。 キャンバス単位でクリップする キャンバス ...

[C# WPF] なんとかしてWPFの描画を速くしたい「DrawRectangleでのPenの有無」
最近WPFのパフォーマンスチューニングに勤しんでいます。 300,000個ほどの ...

[C# WPF] StreamGeometryで破線を描画する
StreamGeometryで破線の描画をしたくなったのですが、Penオブジェク ...

[C# WPF] なんとかしてWPFの描画を速くしたい「Canvas.Childrenへのオブジェクト追加/削除のコスト」
最近WPFのパフォーマンスチューニングに勤しんでいます。 300,000個ほどの ...
ディスカッション
コメント一覧
まだ、コメントがありません