WPF DataGrid排序数据类型为“double”

huangapple go评论65阅读模式
英文:

WPF DataGrid sorting data of type "double"

问题

我遇到了一个问题,我想要在DataGrid中对“double”值进行排序,这些值被知道以“string”的形式存储。

当我按下排序(在表头上),它会将“money total”列的数据按“string”类型进行排序。

WPF DataGrid排序数据类型为“double”

这是我的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)

WPF DataGrid排序数据类型为“double”

Thats my DataGridTextColumn (unfortunately there is no DataGridDoubleColumn)

&lt;DataGridTextColumn Header=&quot;{DynamicResource moneyTotal}&quot; Binding=&quot;{Binding StringMoneyTotal}&quot;/&gt;

Thats my Model (have removed the unimportant code)

public class InvoiceModel
{
    public double MoneyTotal { get; set; }
    public string StringMoneyTotal { get { return String.Format(&quot;{0:0.0,0}&quot;, MoneyTotal); }} 
}

Is there a solution how I can really sort by double? unfortunately the current sorting is useless

答案1

得分: 2

  1. 有两种方法来解决这个问题:

    1. 正如评论中Andy建议的那样,只需绑定到 MoneyTotal(无需使用 StringMoneyTotal),然后单独提供格式化,例如:Binding=&quot;{Binding MoneyTotal, StringFormat={}{0:0.00}}&quot;。 作为替代,您也可以使用 Converter 来实现相同的效果。

    2. 保持绑定不变,但指定按哪个属性排序:SortMemberPath=&quot;MoneyTotal&quot;

英文:

Two ways to fix this:

  1. As suggested by Andy in the comments, just bind to MoneyTotal (no need for StringMoneyTotal) and provide the formatting separately, e.g.: Binding=&quot;{Binding MoneyTotal, StringFormat={}{0:0.00}}&quot;. Alternatively to StringFormatyou could also use a Converter.

  2. Keep the binding as is, but specify by which property to sort: SortMemberPath=&quot;MoneyTotal&quot;

huangapple
  • 本文由 发表于 2023年1月8日 21:46:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048242.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定