问题描述
我使用以下代码在xaml中创建了CheckedListbox:
I've made a CheckedListbox in xaml using this code:
<ListBox Height="340" ItemsSource="{Binding Sections}" SelectedItem="{Binding SelectedSection}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsChecked}" Content="{Binding Path=Item}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
及其绑定到此集合:
public ObservableCollection<CheckedListItem<String>> Sections { get; set; }
private CheckedListItem<String> _selectedSection;
public CheckedListItem<String> SelectedSection
{
get { return _selectedSection; }
set
{
_selectedSection = value;
RaisePropertyChanged("SelectedSection");
}
}
CheckedListItem类如下:
The CheckedListItem class looks like this:
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 =值中设置一个断点;代码的一部分,但是当我在CheckedListBox中选择/取消选择一个项目时,它永远不会触发.
I tried to set a breakpoint in the _selectedSection = value; part of the code but it never gets triggered when i select/deselect an item in the CheckedListBox.
我的问题是,每次选择/取消选择时如何获取所选项目?
My question is how can I get the selected item every time its selected/deselected ?
谢谢
推荐答案
将您的 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>
您可能在复选框
或 square
控件中单击实际的 textblock
控件,而这些控件不会触发 selectionchanged
以获得 listbox
.如果您尝试在矩形的边界之外单击,请说 whitespace
,它将触发.
You are probably clicking on the actual textblock
control inside the checkbox
or the square
control which doesn't trigger selectionchanged
for a listbox
. If you try to click outside the bounds of the rectangle say the whitespace
then it will fire.
如果您只想将复选框
作为数据模板,则将需要做更多的工作,因为您要基于复选框选择/取消选择
listboxitem
'代码> IsChecked 属性.因此,只需将其包装在 ListBoxItem
中,您应该会很好.
It'll be more work if you just want the checkbox
as the datatemplate since you want to select/deselect listboxitem
' based on the checkbox
IsChecked property. So just wrap it inside a ListBoxItem
and you should be good to go.
这篇关于WPF CheckedListbox-如何获取所选项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!