本篇文章给大家分享的是有关如何使用listView,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
一、基本使用:
listView.View = View.Details;//设置视图
listView.SmallImageList = imageList;//设置图标
//添加列
listView.Columns.Add("本地路径", 150, HorizontalAlignment.Left);
listView.Columns.Add("远程路径", 150, HorizontalAlignment.Left);
listView.Columns.Add("上传状态", 80, HorizontalAlignment.Left);
listView.Columns.Add("耗时", 80, HorizontalAlignment.Left);
//添加行
var item = new ListViewItem();
item.ImageIndex = 1;
item.Text = name; //本地路径
item.SubItems.Add(path); //远程路径
item.SubItems.Add("ok"); //执行状态
item.SubItems.Add("0.5"); //耗时统计
listView.BeginUpdate();
listView.Items.Add(item);
listView.Items[listView.Items.Count - 1].EnsureVisible();//滚动到最后
listView.EndUpdate();
二、动态添加记录,ListView不闪烁:
1.新建一个C# 类,命名为ListViewNF(NF=Never/No Flickering)
2.复制如下代码
class ListViewNF : System.Windows.Forms.ListView
{
public ListViewNF()
{
// Activate double buffering
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
// Enable the OnNotifyMessage event so we get a chance to filter out
// Windows messages before they get to the form's WndProc
this.SetStyle(ControlStyles.EnableNotifyMessage, true);
}
protected override void OnNotifyMessage(Message m)
{
//Filter out the WM_ERASEBKGND message
if (m.Msg != 0x14)
{
base.OnNotifyMessage(m);
}
}
}
3.修改你的WinForm对应的xxxx.Design.cs,将系统默认生成的System.Windows.Forms.ListView改为ListViewNF即可。
三、动态添加记录,跳转到最后行:
实现代码:
ListViewItem Item = new ListViewItem();
Item.SubItems.Clear();
.....相关其他代码
this.listView1.Items.Add(Item);
Item.EnsureVisible(); //关键的实现函数
四、点击表头实现排序:
1.增加自定义排序类:
using System;
using System.Collections;
using System.Windows.Forms;
namespace Whir.Software.Framework.UI
{
public class ListViewSort : IComparer
{
private readonly int _col;
private readonly bool _descK;
public ListViewSort()
{
_col = 0;
}
public ListViewSort(int column, object desc)
{
_descK = (bool)desc;
_col = column; //当前列,0,1,2...,参数由ListView控件的ColumnClick事件传递
}
public int Compare(object x, object y)
{
int tempInt = String.CompareOrdinal(((ListViewItem)x).SubItems[_col].Text,
((ListViewItem)y).SubItems[_col].Text);
if (_descK)
{
return -tempInt;
}
return tempInt;
}
}
}
2.给ListView增加点击表头事件:
private void listView_ColumnClick(object sender, ColumnClickEventArgs e)
{
if (listView.Columns[e.Column].Tag == null)
{
listView.Columns[e.Column].Tag = true;
}
var tabK = (bool)listView.Columns[e.Column].Tag;
listView.Columns[e.Column].Tag = !tabK;
listView.ListViewItemSorter = new ListViewSort(e.Column, listView.Columns[e.Column].Tag);
//指定排序器并传送列索引与升序降序关键字
listView.Sort();//对列表进行自定义排序
}
以上就是如何使用listView,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4196063/blog/5008337