我的解决方案是一个类,用于在单击列标题时对listView项目进行排序。
您可以指定每列的类型。
listView.ListViewItemSorter = new ListViewColumnSorter();
listView.ListViewItemSorter.ColumnsTypeComparer.Add(0, DateTime);
listView.ListViewItemSorter.ColumnsTypeComparer.Add(1, int);
这就是了!
C#类:
using System.Collections;
using System.Collections.Generic;
using EDV;
namespace System.Windows.Forms
{
public class ListViewColumnSorter : IComparer
{
private int ColumnToSort;
private SortOrder OrderOfSort;
private CaseInsensitiveComparer ObjectCompare;
public ListViewColumnSorter()
: this(0, SortOrder.None) { }
public ListViewColumnSorter(int columnToSort, SortOrder orderOfSort)
{
ColumnToSort = columnToSort;
OrderOfSort = orderOfSort;
ObjectCompare = new CaseInsensitiveComparer();
ColumnsComparer = new Dictionary<int, IComparer>();
ColumnsTypeComparer = new Dictionary<int, Type>();
}
public int Compare(object x, object y)
{
int compareResult;
ListViewItem listviewX, listviewY;
listviewX = (ListViewItem)x;
listviewY = (ListViewItem)y;
if (listviewX.SubItems.Count < ColumnToSort + 1 || listviewY.SubItems.Count < ColumnToSort + 1)
return 0;
IComparer objectComparer = null;
Type comparableType = null;
if (ColumnsComparer == null || !ColumnsComparer.TryGetValue(ColumnToSort, out objectComparer))
if (ColumnsTypeComparer == null || !ColumnsTypeComparer.TryGetValue(ColumnToSort, out comparableType))
objectComparer = ObjectCompare;
if (comparableType != null) {
object valueX = listviewX.SubItems[ColumnToSort].Text;
object valueY = listviewY.SubItems[ColumnToSort].Text;
if (!edvTools.TryParse(ref valueX, comparableType) || !edvTools.TryParse(ref valueY, comparableType))
return 0;
compareResult = (valueX as IComparable).CompareTo(valueY);
}
else
compareResult = objectComparer.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);
if (OrderOfSort == SortOrder.Ascending) {
return compareResult;
}
else if (OrderOfSort == SortOrder.Descending) {
return (-compareResult);
}
else {
return 0;
}
}
public int SortColumn
{
set
{
ColumnToSort = value;
}
get
{
return ColumnToSort;
}
}
public SortOrder Order
{
set
{
OrderOfSort = value;
}
get
{
return OrderOfSort;
}
}
public Dictionary<int, IComparer> ColumnsComparer { get; set; }
public Dictionary<int, Type> ColumnsTypeComparer { get; set; }
}
}
初始化ListView:
<var>Visual.WIN.ctrlListView.OnShown</var> :
eventSender.Columns.Clear();
eventSender.SmallImageList = edvWinForm.ImageList16;
eventSender.ListViewItemSorter = new ListViewColumnSorter();
var col = eventSender.Columns.Add("Répertoire");
col.Width = 160;
col.ImageKey = "Domain";
col = eventSender.Columns.Add("Fichier");
col.Width = 180;
col.ImageKey = "File";
col = eventSender.Columns.Add("Date");
col.Width = 120;
col.ImageKey = "DateTime";
eventSender.ListViewItemSorter.ColumnsTypeComparer.Add(col.Index, DateTime);
col = eventSender.Columns.Add("Position");
col.TextAlign = HorizontalAlignment.Right;
col.Width = 80;
col.ImageKey = "Num";
eventSender.ListViewItemSorter.ColumnsTypeComparer.Add(col.Index, Int32);
填充 ListView:
<var>Visual.WIN.cmdSearch.OnClick</var> :
..ctrlListView:Items.Clear();
..ctrlListView:Sorting = SortOrder.None;
var group = ..ctrlListView:Groups.Add(DateTime.Now.ToString()
, Path.Combine(..cboDir:Text, ..ctrlPattern1:Text) + " contenant " + ..ctrlSearch1:Text);
var perf = Environment.TickCount;
var files = new DirectoryInfo(..cboDir:Text).GetFiles(..ctrlPattern1:Text)
var search = ..ctrlSearch1:Text;
var ignoreCase = ..Search.IgnoreCase;
var dirLength : int = ..cboDir:Text.Length;
var position : int;
var added : int = 0;
for(var i : int = 0; i < files.Length; i++){
var file = files[i];
if(search == ""
|| (position = File.ReadAllText(file.FullName).IndexOf(String(search)
, StringComparison(ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture))) > =0) {
var item = ..ctrlListView:Items.Add(file.FullName.Substring(dirLength));
item.SubItems.Add(file.Name);
item.SubItems.Add(File.GetLastWriteTime(file.FullName).ToString());
item.SubItems.Add(position.ToString("# ### ##0"));
item.Group = group;
++added;
}
}
group.Header += " : " + added + "/" + files.Length + " fichier(s)"
+ " en " + (Environment.TickCount - perf).ToString("# ##0 msec");
在 ListView 的列点击事件中:
<var>Visual.WIN.ctrlListView.OnColumnClick</var> :
var sorter = eventSender.ListViewItemSorter;
if ( eventArgs.Column == sorter .SortColumn )
{
if (sorter.Order == SortOrder.Ascending)
{
sorter.Order = SortOrder.Descending;
}
else
{
sorter.Order = SortOrder.Ascending;
}
}
else
{
sorter.SortColumn = eventArgs.Column;
sorter.Order = SortOrder.Ascending;
}
eventSender.Sort();
上面使用了edvTools.TryParse函数。
class edvTools {
public static bool TryParse(ref object pValue, System.Type pType)
{
int lIParsed;
double lDParsed;
string lsValue;
if (pValue == null) return false;
if (pType.Equals(typeof(bool))) {
bool lBParsed;
if (pValue is bool) return true;
if (double.TryParse(pValue.ToString(), out lDParsed)) {
pValue = lDParsed != 0D;
return true;
}
if (bool.TryParse(pValue.ToString(), out lBParsed)) {
pValue = lBParsed;
return true;
}
else
return false;
}
if (pType.Equals(typeof(Double))) {
if (pValue is Double) return true;
if (double.TryParse(pValue.ToString(), out lDParsed)
|| double.TryParse(pValue.ToString().Replace(NumberDecimalSeparatorNOT, NumberDecimalSeparator), out lDParsed)) {
pValue = lDParsed;
return true;
}
else
return false;
}
if (pType.Equals(typeof(int))) {
if (pValue is int) return true;
if (Int32.TryParse(pValue.ToString(), out lIParsed)) {
pValue = lIParsed;
return true;
}
else if (double.TryParse(pValue.ToString(), out lDParsed)) {
pValue = (int)lDParsed;
return true;
}
else
return false;
}
if (pType.Equals(typeof(Byte))) {
if (pValue is byte) return true;
byte lByte;
if (Byte.TryParse(pValue.ToString(), out lByte)) {
pValue = lByte;
return true;
}
else if (double.TryParse(pValue.ToString(), out lDParsed)) {
pValue = (byte)lDParsed;
return true;
}
else
return false;
}
if (pType.Equals(typeof(long))) {
long lLParsed;
if (pValue is long) return true;
if (long.TryParse(pValue.ToString(), out lLParsed)) {
pValue = lLParsed;
return true;
}
else if (double.TryParse(pValue.ToString(), out lDParsed)) {
pValue = (long)lDParsed;
return true;
}
else
return false;
}
if (pType.Equals(typeof(Single))) {
if (pValue is float) return true;
Single lSParsed;
if (Single.TryParse(pValue.ToString(), out lSParsed)
|| Single.TryParse(pValue.ToString().Replace(NumberDecimalSeparatorNOT, NumberDecimalSeparator), out lSParsed)) {
pValue = lSParsed;
return true;
}
else
return false;
}
if (pType.Equals(typeof(DateTime))) {
if (pValue is DateTime) return true;
DateTime lDTParsed;
if (DateTime.TryParse(pValue.ToString(), out lDTParsed)) {
pValue = lDTParsed;
return true;
}
else if (pValue.ToString().Contains("UTC"))
{
if (_MonthsUTC == null) InitMonthsUTC();
string[] lDateParts = pValue.ToString().Split(' ');
lDTParsed = new DateTime(int.Parse(lDateParts[5]), _MonthsUTC[lDateParts[1]], int.Parse(lDateParts[2]));
lDateParts = lDateParts[3].ToString().Split(':');
pValue = lDTParsed.AddSeconds(int.Parse(lDateParts[0]) * 3600 + int.Parse(lDateParts[1]) * 60 + int.Parse(lDateParts[2]));
return true;
}
else
return false;
}
if (pType.Equals(typeof(Array))) {
if (pValue is System.Collections.ICollection || pValue is System.Collections.ArrayList)
return true;
return pValue is System.Data.DataTable
|| pValue is string && (pValue as string).StartsWith("<");
}
if (pType.Equals(typeof(DataTable))) {
return pValue is System.Data.DataTable
|| pValue is string && (pValue as string).StartsWith("<");
}
if (pType.Equals(typeof(System.Drawing.Bitmap))) {
return pValue is System.Drawing.Image || pValue is byte[];
}
if (pType.Equals(typeof(System.Drawing.Image))) {
return pValue is System.Drawing.Image || pValue is byte[];
}
if (pType.Equals(typeof(System.Drawing.Color))) {
if (pValue is System.Drawing.Color) return true;
if (pValue is System.Drawing.KnownColor) {
pValue = System.Drawing.Color.FromKnownColor((System.Drawing.KnownColor)pValue);
return true;
}
int lARGB;
if (!int.TryParse(lsValue = pValue.ToString(), out lARGB)) {
if (lsValue.StartsWith("Color [A=", StringComparison.InvariantCulture)) {
foreach (string lsARGB in lsValue.Substring("Color [".Length, lsValue.Length - "Color []".Length).Split(','))
switch (lsARGB.TrimStart().Substring(0, 1)) {
case "A":
lARGB = int.Parse(lsARGB.Substring(2)) * 0x1000000;
break;
case "R":
lARGB += int.Parse(lsARGB.TrimStart().Substring(2)) * 0x10000;
break;
case "G":
lARGB += int.Parse(lsARGB.TrimStart().Substring(2)) * 0x100;
break;
case "B":
lARGB += int.Parse(lsARGB.TrimStart().Substring(2));
break;
default:
break;
}
pValue = System.Drawing.Color.FromArgb(lARGB);
return true;
}
if (lsValue.StartsWith("Color [", StringComparison.InvariantCulture)) {
pValue = System.Drawing.Color.FromName(lsValue.Substring("Color [".Length, lsValue.Length - "Color []".Length));
return true;
}
return false;
}
pValue = System.Drawing.Color.FromArgb(lARGB);
return true;
}
if (pType.IsEnum) {
try {
if (pValue == null) return false;
if (pValue is int || pValue is byte || pValue is ulong || pValue is long || pValue is double)
pValue = Enum.ToObject(pType, pValue);
else
pValue = Enum.Parse(pType, pValue.ToString());
}
catch {
return false;
}
}
return true;
}
}