[英]Get all selected items from a ListBox
How Do you get the selected items from a listbox with checkboxes? 如何从带有复选框的列表框中获取选定的项目?
<ListBox Margin="15" Name="MyListBox"
VerticalAlignment="Stretch"
ItemsSource="{Binding Items}"
SelectionMode="Multiple" IsSynchronizedWithCurrentItem="True">
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="OverridesDefaultStyle" Value="true" />
<Setter Property="SnapsToDevicePixels" Value="true" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<CheckBox Margin="5,2"
IsChecked="{TemplateBinding IsSelected}">
<ContentPresenter />
</CheckBox>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
</ListBox>
My ItemsSource is an observable collection that gets some items added to it. My ItemsSource是一个可观察到的集合,其中添加了一些项目。
public ObservableCollection<string> Items = new ObservableCollection<string>()
{"AAAAA", "BBBBB", "CCCCC", "DDDDD"};
DataContext = DataContext;
MyListBox.ItemsSource = Items;
This shows the items fine, but if I, in my interface then tries to select a couple of the items and get the selected items, I only ever get the first one. 这样可以很好地显示项目,但是如果我在界面中尝试选择几个项目并获得所选项目,那么我只会获得第一个项目。 Why?
为什么?
MyListBox.SelectedItems == "AAAA";
The CheckBox.IsChecked
Binding needs to be TwoWay
, which is not supported by TemplateBinding. CheckBox.IsChecked
绑定需要为TwoWay
,TemplateBinding不支持。 Use a regular Binding
instead (which is TwoWay by default here): 请改用常规
Binding
(默认情况下为TwoWay):
<CheckBox IsChecked="{Binding IsSelected,
RelativeSource={RelativeSource TemplatedParent}}" ...>
<ContentPresenter />
</CheckBox>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.