選択モードを設定する

スポンサーリンク

ListBox コントロールに表示されている項目は選択方法を設定することができます。

選択方法は SelectionMode プロパティに SelectionMode 列挙体を指定して設定します

SelectionMode 列挙体 メンバ名説明 Single 単一の項目を選択できるようにします。 Multiple 複数の項目を選択できるようにします。 Extended ShiftキーやCtrlキーを使用して、複数の項目を選択できるようにします。

下記は、Single, Multiple, Extended と書かれた RadioButton コントロールにあわせて、選択モードを変更する例です。

選択モードを設定する例

XAMLの例

<ListBox SelectionMode="Multiple">
    <ListBoxItem>リンゴ</ListBoxItem>
    <ListBoxItem>ミカン</ListBoxItem>
    <ListBoxItem>バナナ</ListBoxItem>
    <ListBoxItem>パイナップル</ListBoxItem>
    <ListBoxItem>スイカ</ListBoxItem>
    <ListBoxItem>グレープフルーツ</ListBoxItem>
</ListBox>

VBの例

Private Sub RadioButton_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles RadioButton3.Checked, RadioButton2.Checked, RadioButton1.Checked
    '選択されたRadioButtonによってSelectionModeを切り替える
    If RadioButton1.IsChecked Then
        ListBox1.SelectionMode = SelectionMode.Single
    ElseIf RadioButton2.IsChecked Then
        ListBox1.SelectionMode = SelectionMode.Multiple
    Else
        ListBox1.SelectionMode = SelectionMode.Extended
    End If
End Sub

C#の例

private void radioButton_Checked(object sender, RoutedEventArgs e)
{
    // 選択されたRadioButtonによってSelectionModeを切り替える
    if ( (bool)radioButton1.IsChecked )
        listBox1.SelectionMode = SelectionMode.Single;
    else if ( (bool)radioButton2.IsChecked )
        listBox1.SelectionMode = SelectionMode.Multiple;
    else
        listBox1.SelectionMode = SelectionMode.Extended;
}
タイトルとURLをコピーしました