C#中如何判断TextChanged是否是键盘触发的?
我有一种方法
private void textBoxPilot_TextChanged(object sender, TextChangedEventArgs e)
{ ... }
,其中有问题的文本框从用户处获取搜索字符串,并使用每次击键的结果填充 ListBox
。
随后,当从 ListBox
中选择一个项目时,我希望该选择反映在同一个 Textbox
中。但是,我不想触发搜索机制,这会导致 Listbox
忘记其选择。
如何确定 TextChanged
事件是由用户触发(通过键盘或复制/粘贴)还是由其他方法使用 textBoxPilot.Text = "Pilot name";
?
谢谢。
I have a method
private void textBoxPilot_TextChanged(object sender, TextChangedEventArgs e)
{ ... }
where the textbox in question takes a search string from the user and populates a ListBox
with the results on every keystroke.
Subsequently, when an item is picked from the ListBox
, I would like the choice reflected in the same Textbox
. However, I don't want to trigger the search mechanism, which would cause the Listbox
to forget its selection.
How can I determine whether the TextChanged
event was triggered by the user (via they keyboard or maybe copy/paste) or by another method using textBoxPilot.Text = "Pilot name";
?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在我的场景中,用户必须输入文本才能触发自动完成,并且当自动完成再次更改文本时我们不希望重新触发,我使用了文本长度。如果用户复制/粘贴并因此使用键盘一次添加超过 1 个字符,则此操作将不起作用。
在您的场景中,如果您始终知道要跳过的值,那么您可以检查它们:
或
In my scenario where user has to type in text to trigger auto-complete and we didn't want a re-trigger when the auto-complete changes the text again, I used the text lengths. This won't work if user copy/pastes and therefore adds more than 1 character at a time with the keyboard.
In your scenario, if you always know the values you want to skip, then you could check for them instead:
or
如果用户从列表中选择“Pilot name”,则将文本框设置为“Pilot name”。这将导致列表框选择“Pilot name”。所以应该保留选择。你只需要打破递归即可。
If the user selects "Pilot name" from the list, you set the text box to "Pilot name". This will cause the list box to select "Pilot name". So the selection should be kept. You just have to break the recursion.
有点黑客,但是......
bit of a hack, but....
禁用的控件不会触发事件。因此,两个选项是始终禁用更新文本,然后重新启用或创建派生类包装器(使用此方法您仍然可以进行数据绑定)
A disabled control will not fire a event. So two options are either always disable update the text then re-enable or create a derived class wrapper (using this method you could still do data binding)