【问题标题】:How to get checked items from a listbox如何从列表框中获取选中的项目
【发布时间】:2013-05-05 16:47:15
【问题描述】:

我是 WPF 的新手,我试图动态地将一些复选框项目添加到 ListBox,然后单击按钮,我试图从列表框中获取选中的项目。但问题是没有检查项目被提取。以下是列表框的代码

<ListBox HorizontalAlignment="Left" Margin="39.714,179,0,364.318" Name="ListBox1" Width="234" FontSize="16" SelectionMode="Multiple">

            <ListBox.BitmapEffect>
                <DropShadowBitmapEffect />
            </ListBox.BitmapEffect>
            <ListBoxItem>
                <CheckBox Content="Bleeding" Name="CheckBox1"></CheckBox>
            </ListBoxItem>
            <ListBoxItem>
                <CheckBox Content="Bruising or Discoloration" Name="CheckBox2"></CheckBox>
            </ListBoxItem>
<DataTemplate>
                <CheckBox Content="{Binding .}" IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" />
            </DataTemplate>
        </ListBox>

以及我如何获取这些检查项目的代码:

Dim l As New List(Of String)
For Each l1 As ListBoxItem In ListBox1.SelectedItems
    l.Add(l1.Content)
Next

我也提到了这些问题:How to get selected items from listbox has checkboxes in WPF?How to remove checked items from a listbox in WPF?

但没有找到任何解决方案。请告诉我如何实现这一目标。

【问题讨论】:

    标签: .net wpf vb.net checkbox listbox


    【解决方案1】:

    选中复选框不会选择项目,这就是您没有得到预期行为的原因。

    您可以将复选框的IsChecked 属性绑定到列表框项的IsSelected 属性。为此,每个复选框上的绑定应该是:

    IsChecked="{Binging IsSelected, 
                        RelativeSource={RelativeSouce FindAncestor,
                                                      AncestorType={x:Type ListBoxItem}},
                        Mode="TwoWay"}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-03
      • 2015-10-20
      • 1970-01-01
      • 2011-02-26
      • 2011-09-25
      • 1970-01-01
      • 2017-06-09
      • 2017-09-10
      相关资源
      最近更新 更多