WinForm中的ListView项目选择

12

我希望在点击时能够选择ListView中的项目。我还想知道我点击了什么。我使用C#编写WinForms程序。我也想知道如何点击所有行。

3个回答

15

只需处理列表上的 Click 事件,并使用 ListView.SelectedItems 属性获取所选项:

private void listView1_Click(object sender, EventArgs e)
{
    var firstSelectedItem = listView1.SelectedItems[0];
}

如果我在同一项上点击两次,它会触发两次事件,但实际上选择并没有改变,所以不应该这样。 - Totty.js

3
您可以使用MouseEventArgs获取鼠标位置并检查它是否存在于所选项目绑定内,这意味着单击是在所选项目上进行的。
    private void myList_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        if (myList.SelectedItems.Count  >= 1)
        {
            ListViewItem item = myList.SelectedItems[0];

            //here i check for the Mouse pointer location on click if its contained 
            // in the actual selected item's bounds or not .
            // cuz i ran into a problem with the ui once because of that ..
            if (item.Bounds.Contains(e.Location))
            {
                MessageBox.Show("Double Clicked on :"+item.Text);
            }
        }
    }

0

如果您在窗口中使用XAML,则必须将MouseUp="listView1_Click"属性添加到ListView标记


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接