键盘焦点到 WPF 中的列表框项目 [英] Keyboard focus to list box items in WPF

查看:24
本文介绍了键盘焦点到 WPF 中的列表框项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表框,它的项目模板有一个复选框.现在,当我单击列表框中的复选框时,它会设置复选框的选中状态.如果我使用键盘空格"键,我无法更改复选框状态.

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.

推荐答案

如果您根本不希望 ListBox 提供选择,您可以使用普通的 ItemsControl 代替 ListBox:

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>

然后,您将只拥有一系列 CheckBox,而无需使用将获取键盘焦点的 ListBoxItem 控件包装它们.

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

另一方面,如果您希望 ListBox 显示选择,那么您可能需要一个多选 ListBox,其中 CheckBox 的状态绑定到 ListBoxItem 的选定状态.由于单击 ListBoxItem 将检查 CheckBox,因此您可以完全阻止 CheckBox 获得焦点:

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>

这篇关于键盘焦点到 WPF 中的列表框项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆