[英]Set focus on ListView
I've just starting using ListView control in VS2019.我刚刚开始在 VS2019 中使用 ListView 控件。
I'm sure there's a simple solution, but I can't figure out how to set the focus on the control like I can with most other controls.我确信有一个简单的解决方案,但我不知道如何像使用大多数其他控件一样将焦点设置在控件上。
I want the ListView to be focused when the form loads, and then I want to programmatically focus an item in the ListView.我希望在表单加载时将 ListView 聚焦,然后我想以编程方式聚焦 ListView 中的项目。
I know how to focus a particular item using ListView1.FocusedItem.Index
, but I can't focus the actual control.我知道如何使用
ListView1.FocusedItem.Index
聚焦特定项目,但我无法聚焦实际控制。
I have tried both ListView1.Select()
and ListView1.Focus()
but these seem to do nothing.我已经尝试过
ListView1.Select()
和ListView1.Focus()
但这些似乎什么也没做。
What am I missing??我错过了什么??
Thanks谢谢
EDIT As pointed out below, the control is actually focused using ListView1.Select() it's just not focused in the same way I'd expect, for example, a ListBox to be focused - ie, with a particular item in the list highlighted.编辑正如下面所指出的,控件实际上是使用 ListView1.Select() 聚焦的,它只是没有以我期望的方式聚焦,例如,一个 ListBox 聚焦 - 即,突出显示列表中的特定项目。
How would you best focus the ListView and highlight a particular item?您将如何最好地聚焦 ListView 并突出显示特定项目? I have tried this in a command button on the form, but it doesn't do anything.
我已经在表单上的命令按钮中尝试过这个,但它没有做任何事情。 Though it works correctly AFTER I click an Item in the ListView.
尽管在我单击 ListView 中的项目后它可以正常工作。
ListView1.Select()
If (ListView1.SelectedItems.Count > 0) Then
ListView1.Items(4).Selected = True
End If
ListView1.Select
works, you probably just don't see that the ListView has focus. ListView1.Select
有效,您可能只是没有看到 ListView 有焦点。 You can verify this by checking the GotFocus and LostFocus events on the ListView:您可以通过检查 ListView 上的 GotFocus 和 LostFocus 事件来验证这一点:
Private Sub ListView1_GotFocus(sender As Object, e As EventArgs) Handles ListView1.GotFocus
Me.Text = "Got Focus"
End Sub
Private Sub ListView1_LostFocus(sender As Object, e As EventArgs) Handles ListView1.LostFocus
Me.Text = "Lost Focus"
End Sub
This simply updates your Form's title to "Got Focus" or "Lost Focus".这只是将表单的标题更新为“Got Focus”或“Lost Focus”。 You can force the focus in your Form Load event:
您可以在 Form Load 事件中强制获得焦点:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
ListView1.Items.Add("a")
ListView1.Items.Add("b")
ListView1.Items.Add("c")
ListView1.Select()
End Sub
listview1.focus()
For I as Integer = 0 to ListView1.Items.Count - 1
If ListView1.Items(i).Text = "youritemtexthere" then
ListView1.Items(i).Selected = true
End If
End For
or if you have the index but not a known text just do:或者如果您有索引但没有已知文本,请执行以下操作:
listview1.focus()
ListView1.Items(index).Selected = true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.