自定义listview中的代码分析

  public int GetSubItemAt(int x, int y, out ListViewItem item)
  {
   item = this.GetItemAt(x, y);
  
   if (item != null)
   {
    int[] order = GetColumnOrder();
    Rectangle lviBounds;
    int subItemX;

    lviBounds = item.GetBounds(ItemBoundsPortion.Entire);
    subItemX = lviBounds.Left;
    for (int i=0; i<order.Length; i++)
    {
     ColumnHeader h = this.Columns[order[i]];
     if (x < subItemX+h.Width)
     {
      return h.Index;
     }
     subItemX += h.Width;
    }
   }
   
   return -1;
  }

 

 

GetItemAt 方法使您可以确定哪个项位于 ListView 控件的工作区域中的特定位置。当用户单击或用鼠标右键单击子项(当 View 属性设置为 View.Details 时),并且您要在用户单击鼠标时根据鼠标坐标来确定是哪个项拥有被单击的子项时,可以使用该方法。

 

 

列标头是 ListView 控件中包含标头文本的项。可以使用 ListView.ColumnHeaderCollection 类的 Add 方法将 ColumnHeader 对象添加到 ListView。若要将一组列添加到 ListView,可以使用 ListView.ColumnHeaderCollection 类的 AddRange 方法。可以使用 ColumnHeader 类的 Index 属性确定 ColumnHeaderListView.ColumnHeaderCollection 中的位置。

ColumnHeader 提供 TextTextAlign 属性来设置控件中显示的文本以及列标头中文本的对齐方式。若要确定某个 ColumnHeader 是否与某 ListView 控件关联,可以引用 ListView 属性。如果您想复制一个 ColumnHeader 以供在另一 ListView 控件中使用,可以使用 Clone 方法。

下面的代码示例演示如何初始化 ListView 控件。该示例创建 ColumnHeader 对象并设置列标题的 TextTextAlignWidth 属性。该示例还向 ListView 中添加项和子项。若要运行此示例,请将以下代码粘贴到一个窗体中,并从该窗体的构造函数或 Load 事件处理程序中调用 PopulateListView 方法。

private void PopulateListView()
{
    ListView1.Width = 270;
    ListView1.Location = new System.Drawing.Point(10, 10);

    // Declare and construct the ColumnHeader objects.
    ColumnHeader header1, header2;
    header1 = new ColumnHeader();
    header2 = new ColumnHeader();

    // Set the text, alignment and width for each column header.
    header1.Text = "File name";
    header1.TextAlign = HorizontalAlignment.Left;
    header1.Width = 70;

    header2.TextAlign = HorizontalAlignment.Left;
    header2.Text = "Location";
    header2.Width = 200;

    // Add the headers to the ListView control.
    ListView1.Columns.Add(header1);
    ListView1.Columns.Add(header2);

    // Populate the ListView.Items property.
    // Set the directory to the sample picture directory.
    System.IO.DirectoryInfo dirInfo = 
        new System.IO.DirectoryInfo(
        "C://Documents and Settings//All Users" +
        "//Documents//My Pictures//Sample Pictures");
    

    // Get the .jpg files from the directory
    System.IO.FileInfo[] files = dirInfo.GetFiles("*.jpg");

    // Add each file name and full name including path
    // to the ListView.
    if (files != null)
    {
        foreach ( System.IO.FileInfo file in files )
        {
            ListViewItem item = new ListViewItem(file.Name);
            item.SubItems.Add(file.FullName);
            ListView1.Items.Add(item);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值