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.
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. Use a regular Binding
instead (which is TwoWay by default here):
<CheckBox IsChecked="{Binding IsSelected,
RelativeSource={RelativeSource TemplatedParent}}" ...>
<ContentPresenter />
</CheckBox>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.