WPF ListBoxItem选择问题 [英] WPF ListBoxItem selection problem
问题描述
我有一个列表框,其中的项目包含复选框:
I have a listbox where the items contain checkboxes:
<ListBox Style="{StaticResource CheckBoxListStyle}" Name="EditListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Click="Checkbox_Click" IsChecked="{Binding Path=IsChecked, Mode=TwoWay}" Content="{Binding Path=DisplayText}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我遇到的问题是,当我单击复选框或其内容时,父ListBoxItem未被选中.如果我单击复选框旁边的空白,则ListBoxItem确实会被选中.
The problem I'm having is that when I click on the checkbox or its content, the parent ListBoxItem does not get selected. If I click on the white space next to the checkbox, the ListBoxItem does get selected.
我试图获得的行为是能够选择列表中的一个或多个项目,并使用空格键来打开或关闭复选框.
The behavior that I'm trying to get is to be able to select one or many items in the list and use the spacebar to toggle the checkboxes on and off.
更多信息:
private void Checkbox_Click(object sender, RoutedEventArgs e)
{
CheckBox chkBox = e.OriginalSource as CheckBox;
}
在上面的代码中,当我单击一个复选框时,e.Handled为false,chkBox.Parent为null.
In the code above when I click on a checkbox, e.Handled is false and chkBox.Parent is null.
肯特的答案使我走上了正确的道路,这就是我最终得到的结果:
Kent's answer put me down the right path, here's what I ended up with:
<ListBox Style="{StaticResource CheckBoxListStyle}" Name="EditListBox" PreviewKeyDown="ListBox_PreviewKeyDown">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding Path=IsChecked, Mode=TwoWay}" />
<TextBlock Text="{Binding DisplayText}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我必须使用PreviewKeyDown,因为默认情况下,当您单击列表框中的空格键时,它将取消选择除最近选择的项目以外的所有内容.
I had to use PreviewKeyDown because by default when you hit the spacebar in a list box, it deselects everything except for the most recently selected item.
推荐答案
首先,将内容放在CheckBox
之外:
To begin with, put the content outside the CheckBox
:
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsChecked}"/>
<TextBlock Text="{Binding DisplayText}"/>
</StackPanel>
此后,您需要确保按下ListBoxItem
上的空格会导致检查CheckBox
.有许多方法可以做到这一点,包括ListBoxItem
上的简单事件处理程序.或者,您可以为UIElement.KeyUp
或DataTemplate
中的任何内容指定处理程序:
After that, you will need to ensure that pressing space on a ListBoxItem
results in the CheckBox
being checked. There are a number of ways of doing this, including a simple event handler on the ListBoxItem
. Or you could specify a handler for UIElement.KeyUp
or whatever in your DataTemplate
:
<CheckBox IsChecked="{Binding IsChecked}" UIElement.KeyUp="..."/>
这篇关于WPF ListBoxItem选择问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!