如何从带有复选框的列表框中获取所选项目?
<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是一个可观察的集合,可以添加一些项目。
public ObservableCollection<string> Items = new ObservableCollection<string>()
{"AAAAA", "BBBBB", "CCCCC", "DDDDD"};
DataContext = DataContext;
MyListBox.ItemsSource = Items;
这显示项目很好,但如果我,在我的界面中然后尝试选择几个项目并获取所选项目,我只得到第一个。为什么呢?
MyListBox.SelectedItems == "AAAA";
答案 0 :(得分:2)
CheckBox.IsChecked
绑定需要TwoWay
,而TemplateBinding不支持。使用常规Binding
代替(默认情况下为TwoWay):
<CheckBox IsChecked="{Binding IsSelected,
RelativeSource={RelativeSource TemplatedParent}}" ...>
<ContentPresenter />
</CheckBox>