Keyboard focus to list box items in WPF [duplicate]

懵懂的女人 提交于 2019-11-30 20:43:19

问题


I am having a list box, and its item template is having one check box. Now, when I click on the check box in the listbox, it sets the checked status of the check box. If I use keyboard "Space" key, I cannot change the checkbox state.

Note: Keyboard is shortcut is working once I set focus to the check box by clicking it.


回答1:


If you don't want the ListBox to provide selection at all, you could use a plain ItemsControl instead of a ListBox:

<ItemsControl ItemsSource="{Binding}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Then you will just have a sequence of CheckBoxes without wrapping them with ListBoxItem controls that will take the keyboard focus.

On the other hand, if you want the ListBox to display selection, then maybe you want a multi-select ListBox where the state of the CheckBox is bound to the selected state of the ListBoxItem. Since clicking the ListBoxItem will check the CheckBox, you could prevent the CheckBox from being focused at all:

<ListBox ItemsSource="{Binding}" SelectionMode="Multiple">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox
                Content="{Binding}"
                Focusable="False"
                IsChecked="{Binding IsSelected, RelativeSource=
                    {RelativeSource AncestorType={x:Type ListBoxItem}}}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>


来源:https://stackoverflow.com/questions/3156122/keyboard-focus-to-list-box-items-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!