我使用这段代码在 xaml 中制作了一个 CheckedListbox:
<ListBox Height="340" ItemsSource="{Binding Sections}" SelectedItem="{Binding SelectedSection}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsChecked}" Content="{Binding Path=Item}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
它绑定(bind)到这个集合:
public ObservableCollection<CheckedListItem<String>> Sections { get; set; }
private CheckedListItem<String> _selectedSection;
public CheckedListItem<String> SelectedSection
{
get { return _selectedSection; }
set
{
_selectedSection = value;
RaisePropertyChanged("SelectedSection");
}
}
CheckedListItem 类如下所示:
public class CheckedListItem<T> : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private bool isChecked;
private T item;
public CheckedListItem()
{ }
public CheckedListItem(T item, bool isChecked = false)
{
this.item = item;
this.isChecked = isChecked;
}
public T Item
{
get { return item; }
set
{
item = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Item"));
}
}
public bool IsChecked
{
get { return isChecked; }
set
{
isChecked = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("IsChecked"));
}
}
}
我试图在 _selectedSection = value; 中设置一个断点;代码的一部分,但当我选择/取消选择 CheckedListBox 中的项目时它永远不会被触发。
我的问题是每次选择/取消选择时如何获取所选项目?
谢谢
最佳答案
更改您的 XAML
到
<ListBox Height="340" ItemsSource="{Binding Sections}" SelectedItem="{Binding SelectedSection}">
<ListBox.ItemTemplate>
<DataTemplate>
<ListBoxItem IsSelected="{Binding IsChecked}">
<CheckBox IsChecked="{Binding IsChecked}" Content="{Binding Path=Item}" />
</ListBoxItem>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
您可能正在单击实际的 textblock
checkbox
里面的控件或 square
控制不触发 selectionchanged
对于 listbox
.如果您尝试在矩形边界外单击,请说 whitespace
然后它会开火。
如果你只想要 checkbox
会更麻烦作为数据模板,因为您要选择/取消选择 listboxitem
' 基于 checkbox
IsChecked 属性。所以只需将它包裹在 ListBoxItem
中你应该可以开始了。
关于c# - Wpf CheckedListbox - 如何获取所选项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21193242/