从 ListBox 中获取所有选中的项目
Get all selected items from a ListBox
如何从带有复选框的列表框中获取 selected 项?
MainWindow.xaml
<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>
我的 ItemsSource 是一个可观察的集合,可以向其中添加一些项目。
MainWindow.xaml.cs
public ObservableCollection<string> Items = new ObservableCollection<string>()
{"AAAAA", "BBBBB", "CCCCC", "DDDDD"};
DataContext = DataContext;
MyListBox.ItemsSource = Items;
这显示项目很好,但如果我在我的界面中尝试 select 几个项目并获得 selected 项目,我只会得到第一个。为什么?
MyListBox.SelectedItems == "AAAA";
CheckBox.IsChecked
绑定需要TwoWay
,TemplateBinding不支持。请改用常规 Binding
(此处默认为 TwoWay):
<CheckBox IsChecked="{Binding IsSelected,
RelativeSource={RelativeSource TemplatedParent}}" ...>
<ContentPresenter />
</CheckBox>
如何从带有复选框的列表框中获取 selected 项?
MainWindow.xaml
<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>
我的 ItemsSource 是一个可观察的集合,可以向其中添加一些项目。
MainWindow.xaml.cs
public ObservableCollection<string> Items = new ObservableCollection<string>()
{"AAAAA", "BBBBB", "CCCCC", "DDDDD"};
DataContext = DataContext;
MyListBox.ItemsSource = Items;
这显示项目很好,但如果我在我的界面中尝试 select 几个项目并获得 selected 项目,我只会得到第一个。为什么?
MyListBox.SelectedItems == "AAAA";
CheckBox.IsChecked
绑定需要TwoWay
,TemplateBinding不支持。请改用常规 Binding
(此处默认为 TwoWay):
<CheckBox IsChecked="{Binding IsSelected,
RelativeSource={RelativeSource TemplatedParent}}" ...>
<ContentPresenter />
</CheckBox>