英文:
WPF DataGrid sorting data of type "double"
问题
我遇到了一个问题,我想要在DataGrid中对“double”值进行排序,这些值被知道以“string”的形式存储。
当我按下排序(在表头上),它会将“money total”列的数据按“string”类型进行排序。
这是我的DataGridTextColumn(不幸的是没有DataGridDoubleColumn)
<DataGridTextColumn Header="{DynamicResource moneyTotal}" Binding="{Binding StringMoneyTotal}"/>
这是我的模型(已删除不重要的代码部分)
public class InvoiceModel
{
public double MoneyTotal { get; set; }
public string StringMoneyTotal { get { return String.Format("{0:0.0,0}", MoneyTotal); }}
}
是否有解决办法可以真正按double类型进行排序?不幸的是,当前的排序是无用的。
英文:
I have run into a problem
that I want to sort a "double" value in the DataGrid, these values are known to be stored as "string".
When I press sort (on the header), then it sorts the data from the column "money total" as type "string".
(see here)
Thats my DataGridTextColumn (unfortunately there is no DataGridDoubleColumn)
<DataGridTextColumn Header="{DynamicResource moneyTotal}" Binding="{Binding StringMoneyTotal}"/>
Thats my Model (have removed the unimportant code)
public class InvoiceModel
{
public double MoneyTotal { get; set; }
public string StringMoneyTotal { get { return String.Format("{0:0.0,0}", MoneyTotal); }}
}
Is there a solution how I can really sort by double? unfortunately the current sorting is useless
答案1
得分: 2
-
有两种方法来解决这个问题:
-
正如评论中Andy建议的那样,只需绑定到
MoneyTotal
(无需使用StringMoneyTotal
),然后单独提供格式化,例如:Binding="{Binding MoneyTotal, StringFormat={}{0:0.00}}"
。 作为替代,您也可以使用Converter
来实现相同的效果。 -
保持绑定不变,但指定按哪个属性排序:
SortMemberPath="MoneyTotal"
。
-
英文:
Two ways to fix this:
-
As suggested by Andy in the comments, just bind to
MoneyTotal
(no need for StringMoneyTotal) and provide the formatting separately, e.g.:Binding="{Binding MoneyTotal, StringFormat={}{0:0.00}}"
. Alternatively toStringFormat
you could also use aConverter
. -
Keep the binding as is, but specify by which property to sort:
SortMemberPath="MoneyTotal"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论