我正在尝试通过编程方式选择ListView中的第一项,但似乎并没有被选中。 我正在使用以下代码:
if (listView1.Items.Count > 0)
listView1.Items[0].Selected = true;
其实我以前遇到过这个问题,但是我不记得我是怎么解决的了!
很可能,该项已被选择,只是因为其他控件拥有焦点,所以你无法看到。根据你的应用程序设计,有几种不同的解决方法可供选择。
The simple solution is to set the focus to the ListView
first whenever your form is displayed. The user typically sets focus to controls by clicking on them. However, you can also specify which controls gets the focus programmatically. One way of doing this is by setting the tab index of the control to 0 (the lowest value indicates the control that will have the initial focus). A second possibility is to use the following line of code in your form's Load
event, or immediately after you set the Selected
property:
myListView.Select();
The problem with this solution is that the selected item will no longer appear highlighted when the user sets focus to a different control on your form (such as a textbox or a button).
To fix that, you will need to set the HideSelection
property of the ListView
control to False. That will cause the selected item to remain highlighted, even when the control loses the focus.
When the control has the focus, the selected item's background will be painted with the system highlight color. When the control does not have the focus, the selected item's background will be painted in the system color used for grayed (or disabled) text.
You can set this property either at design time, or through code:
myListView.HideSelection = false;
if (listView1.Items.Count > 0)
{
listView1.Items[0].Selected = true;
listView1.Select();
}
除非控件拥有焦点(或您将 HideSelection
属性设置为 false),否则列表项不会显示为选定状态。
我知道这是一个老问题,但我认为这是最终的答案。
listViewRamos.Items[i].Focused = true;
listViewRamos.Items[i].Selected = true;
listViewRemos.Items[i].EnsureVisible();
如果有可能控件没有焦点但你想强制让控件获得焦点,你可以添加以下代码。
listViewRamos.Select();
为什么微软不直接添加一个SelectItem()
方法来代替这一切,这超出了我的理解范围。
我认为问题和解决方案已经被Cody Gray描述得很清楚了!我有一个额外的注释。
请检查指定列表视图项(以及控件)的焦点。我可以通过以下代码设置焦点和选择:
this.listView1.Items[1].Selected = true;
this.listView1.Items[1].Focused = true;
Focused
属性来确定哪个项目是这样的,就像您在这里所做的那样。当仅选择了ListView
中的一个项目时,每当其宿主控件具有焦点时,它将始终具有焦点。 - Cody Gray int i=99;//is what row you want to select and focus
listViewRamos.FocusedItem = listViewRamos.Items[0];
listViewRamos.Items[i].Selected = true;
listViewRamos.Select();
listViewRamos.EnsureVisible(i);//This is the trick
EnsureVisible()
也同样重要。 - Steve Smithif (listView1.Items.Count > 0)
{
listView1.FocusedItem = listView1.Items[0];
listView1.Items[0].Selected = true;
listView1.Select();
}
ListViewItem.IsSelected = true;
ListViewItem.Focus();
UsersLst.Items[index].EnsureVisible();
以显示该元素。 - Ruben Giaquinto