如何以编程方式选择 ListView 中的项目? [英] How to select an item in a ListView programmatically?

查看:33
本文介绍了如何以编程方式选择 ListView 中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图以编程方式选择 ListView 中的第一项,但它似乎没有被选中.我正在使用以下代码:

I'm trying to select the first item in a ListView programmatically, but it doesn't appear to have been selected. I am using the following code:

if (listView1.Items.Count > 0)
    listView1.Items[0].Selected = true;

其实我以前也遇到过这个问题,但我不记得我是怎么解决的!

Actually I've had this problem before but I can't remember how I managed to solve it!

推荐答案

最有可能的是,项目正在被选中,您只是无法分辨,因为不同的控件具有焦点.有几种不同的方法可以解决此问题,具体取决于应用程序的设计.

Most likely, the item is being selected, you just can't tell because a different control has the focus. There are a couple of different ways that you can solve this, depending on the design of your application.

  1. 简单的解决方案是在显示表单时首先将焦点设置到 ListView.用户通常通过单击控件来设置焦点.但是,您也可以指定哪些控件以编程方式获得焦点.一种方法是将控件的选项卡索引设置为 0(最低值表示将具有初始焦点的控件).第二种可能性是在表单的 Load 事件中使用以下代码行,或者在设置 Selected 属性后立即使用:

  1. 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).

要解决此问题,您需要设置 HideSelection 属性 ListView 控件为 False.这将导致所选项目保持突出显示,即使控件失去焦点.

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;

这篇关于如何以编程方式选择 ListView 中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆