当按下无代码隐藏的键时将焦点设置在另一个控件上
我正在实现类似自动建议控件的东西:我有一个包含 TextBox
和 ListBox
的用户控件。当用户输入文本时,我使用 System.Windows.Interactivity
行为来处理它,并用一些值填充 ListBox
...
一切正常...但我想要使用户能够在按下向下箭头键时选择 ListBox
中的项目(即在 ListBox
上设置 Focus
)。
我知道可以在代码隐藏 .cs 文件中处理 TextBox
的 KeyPressDown
事件,但如何避免这种情况?
I'm implementing something like an autosuggestion control: I have a user control that contains a TextBox
and a ListBox
. When the user enters text I'm handing it with System.Windows.Interactivity
behaviors and filling the ListBox
with some values...
Everything works fine... but I want to enable the user to select items in the ListBox
(i.e. to set Focus
on the ListBox
) when the down arrow key is pressed.
I know that it is possible to handle the KeyPressDown
event of the TextBox
in the code-behind .cs file but how can I avoid this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您已经使用了交互性,那么这应该不是什么大问题,只需实现您自己的具有属性
Key
& 的TriggerAction
即可。TargetName
来确定何时以及关注什么。在PreviewKeyDown
的EventTrigger
中设置它。示例实施&使用:
测试它并且它有效,请注意
KeyDown
不会,因为箭头键被拦截并标记为由 TextBox 处理。If you already use Interactivity that should not be much of an issue, just implement your own
TriggerAction
that has the propertiesKey
&TargetName
to indentify when and what to focus. Set it in anEventTrigger
forPreviewKeyDown
.Sample implementation & use:
Tested it and it works, note that
KeyDown
does not because the arrow keys are intercepted and marked as handled by the TextBox.我认为你无法避免它
捕获 TextBox 的
KeyDown
事件有什么问题,如果它是向上或向下箭头键,只需触发ListBox.KeyDown
事件在后面的代码中?如果要提供特定于视图的功能(例如焦点),我认为没有理由不在 MVVM 中使用代码隐藏
I don't think you can avoid it
What's wrong with capturing the
KeyDown
event of the TextBox and if it's an Up or Down arrow key, just trigger theListBox.KeyDown
event in the code behind?I see no reason not to use code-behind in MVVM if it is to provide view-specific functionality such as focus
该答案基于 HB 的答案,并添加了对检查是否按下 Ctrl 键的支持。这意味着它可以处理组合键,例如 Ctrl-F 进行查找。
XAML
命名空间
请参阅有关添加
System.Windows.Interactivity 的帮助
。
依赖属性
This answer is based on the one from
H.B.
, and adds support for checking to see if the Ctrl key is pressed. This means it can handle keycombinations such as Ctrl-F for find.XAML
Namespaces
See help on adding
System.Windows.Interactivity
.DependencyProperty