简体   繁体   English

如何在WPF Listview列中将字符串列排序更改为十进制排序

[英]How to change string column sorting to decimal sorting in WPF Listview column

I have another issue with sorting numbers which are actually string [varchar] from DB. 我还有另一个排序数字的问题,这些数字实际上是数据库中的字符串[varchar]。 In the WPF listview, the cell template is having a textbox. 在WPF列表视图中,单元格模板具有一个文本框。

When the data is loaded in the listview from the DB, the listview Salary column is binded to the salary column in the data table. 当从数据库将数据加载到列表视图中时,列表视图Salary列将绑定到数据表中的salary列。 Due to some other business logic, this salary column in the database table is varchar. 由于其他一些业务逻辑,数据库表中的薪水列为varchar。

But when it is shown in the listview, salary is shown as "456.56" like floating or decimal numbers in the salary cell column in the listview. 但是,当它显示在列表视图中时,薪水显示为“ 456.56”,就像列表视图中薪水单元格列中的浮点数或十进制数字一样。 Since the underlying data source is the data table, Salary column is a varchar datatype !! 由于基础数据源是数据表,因此Salary列是varchar数据类型! So when sorting the listview salary column, it is not sorting the salary column exactly like numbers !! 因此,在对listview薪水列进行排序时,它并不是完全按照数字对薪水列进行排序!

Can I use an IComparer in this case ? 在这种情况下可以使用IComparer吗? If so, how ? 如果是这样,怎么办? any example is much helpful !! 任何例子都是有帮助的!

Why don't you just iterate through the data, either when you retrieve it, or in the view model before you display it and parse the data to the correct data type? 在显示数据并将其解析为正确的数据类型之前,为什么不仅仅在访问数据时或者在视图模型中对数据进行迭代? Then you can let the ListView do the sorting: 然后,您可以让ListView进行排序:

foreach (YourDataType item in yourItemCollection)
{
    YourDisplayDataType displayItem = new YourDisplayDataType(item.Property1, 
        item.Property2, decimal.Parse(item.DecimalVarcharProperty));
}

Of course, if you do this, you'll need to ensure that the decimal VARCHAR values coming from the database are actually all decimal values. 当然,如果你这样做,你需要确保decimal VARCHAR值来自数据库实际上所有十进制值。 If not, you could do the above in two stages: 如果没有,您可以分两个阶段进行上述操作:

foreach (YourDataType item in yourItemCollection)
{
    decimal decimalValue = 0;
    decimal.TryParse(item.DecimalVarcharProperty, out decimalValue);
    YourDisplayDataType displayItem = new YourDisplayDataType(item.Property1, 
        item.Property2, decimalValue);
}

Disclaimer: I can't check this in a compiler at present, so there may be an error... please let me know if that is the case and I will update the answer. 免责声明:我目前无法在编译器中检查此情况,因此可能存在错误...如果是这种情况,请告诉我,我将更新答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM