WPF列表框键盘导航和选择项

WPF列表框键盘导航和选择项

本文介绍了WPF列表框键盘导航和选择项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!

我有一个列表框,它通过datatemplate显示数据收集(我将每个数据显示为自定义按钮).我需要使用键盘遍历列表框项目,并执行Enter press event.问题是列表框根本不会重复输入.如果我用鼠标选择列表框项目,然后按Enter即可.

这是我的问题的简化摘要,显示出完全相同的行为.

Hi all!

I have listbox which shows datacollection via datatemplate (I present each data as customized button). I need to iterract listbox items with keyboard and do Enter press event. Problem is that listbox does not iterract enter press at all. If I choose listbox item by mouse and the press enter it works.

Here is simplified snippet of my problem which shows exact same behaviour.

<ListBox>
         <ListBoxItem>
             <Button Content="ClicMe1" Click="Button_Click"></Button>
         </ListBoxItem>
         <ListBoxItem>
             <Button Content="ClicMe2" Click="Button_Click"></Button>
         </ListBoxItem>
         <ListBoxItem>
             <Button Content="ClicMe3" Click="Button_Click"></Button>
         </ListBoxItem>
     </ListBox>



和代码隐藏



and codebehind

private void Button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("event received");
        }       



Mouseclick可以工作,但是键盘导航到按钮并输入按不会,除非我先用鼠标选择它.

希望你有主意:)

更新:

好的,就像韦恩·盖拉德(Wayne Gaylard)所建议的那样,在我可以访问按钮之前,按两次Tab键会出现想要的行为.这是不幸的,因为我不确定最终用户不会弄清楚它,并且在这种情况下不能单击鼠标.

现在,我尝试在SelectionChanged事件中进行一些自动化以将焦点自动聚焦到按钮上,但到目前为止没有成功.忠告不胜感激:)!

干杯!



Mouseclick works but keyboard navigation to button and enter press wont, unless I choose it by mouse first.

Hope you got idea :)

UPDATE:

OK, just like Wayne Gaylard suggested I get wanted behaviour when I press twice tab key before I can access to button. This is unfortunate because im sure that end user wont figure it out and mouse click is not option in this case.

Now im trying some automation in SelectionChanged event to focus to button automatically but so far no success. Advices appreciated :)!

Cheers!

推荐答案


<Style x:Key="{x:Type ListBoxItem}" TargetType="ListBoxItem">
    <Setter Property="Focusable" Value="False"/>
</Style>



键盘导航现在似乎可以正常工作,只有奇怪的行为是,当您再次从列表框selecteditem高亮后面的代码中设置选定的索引/项目时,除了我的按钮以外,我还不想做其他代码.



keyboard navigation seems to work now, only odd behaviour is now that when you set selected index / item from code behind listbox selecteditem highligths again something else than my button but I think I wont do codebehind selections.


这篇关于WPF列表框键盘导航和选择项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 13:41