【问题标题】:How do I Format string as percentage using converter如何使用转换器将字符串格式化为百分比
【发布时间】:2015-04-08 18:45:14
【问题描述】:

我想从自定义转换器设置属性 ContentStringFormat 将 DataGrid 中的一些小数格式化为百分比。:

<Setter Property="ContentStringFormat">
<Setter.Value>
    <MultiBinding Converter="{StaticResource PercentageConverter}">
        <Binding Path="ItemsSource" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}" />
        <Binding RelativeSource="{RelativeSource Self}" />
        <Binding />
    </MultiBinding>
</Setter.Value>

我已设法添加条件,以便格式仅适用于某些单元格。但是..我不知道返回什么,我试过return {0:P2}但是没有效果:

class PercentageConverter
...
   public object Convert(...)
    if (myCustomConditions)
    {
        return "{0:P2}" // how to return my format??
    }

我需要返回什么来设置 ContentStringFormat?非常感谢您的帮助!

【问题讨论】:

  • 我觉得this 可能对你有帮助。
  • 您好 maam27,感谢您的回复。接受的答案是在 DataGridTextColumn 的定义中设置格式。就我而言,我不知道设计时的列数。而且我不希望格式适用于整个列,而只适用于满足某些条件的DataGridCells。
  • 我认为您可以在 AutogeneratingColumn 事件中添加某些条件(如果使用 MVVM,则使用 E​​ventTrigger)并为特定列设置字符串格式。你可以让其他列也这样。
  • 嗨 Karuppasamy,我之前在另一个场景中使用过你的建议,但现在我真的需要在 DataGridCell 级别设置格式。我需要格式化的不是一整列,而只是那些符合我条件的 DataGridCells。
  • 我刚刚提供了一个类似帖子的链接,其中有一个关于如何在专栏中进行操作的遮篷,我觉得他们赞成评论,因为它对试图设置事物的人有帮助为百分比。尽管您的问题似乎需要代码来查找特定单元格而不仅仅是整个列。

标签: c# wpf


【解决方案1】:

最后,我操纵了绑定源,并以我想要的格式从双精度转换为字符串。对于排序,我实现了一个自定义排序器,它将字符串转换回双精度。

丑陋,但对我来说足够漂亮。

【讨论】:

    【解决方案2】:

    或者,您可以将该值乘以 100 并在末尾附加 % 符号,然后在转换回时除以 100 ..

    Public Function Convert(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As CultureInfo) As Object Implements IValueConverter.Convert
            If TypeOf value Is Double OrElse TypeOf value Is Decimal Then
                Return value * 100
            Else
                Return 0
            End If
        End Function
    
        Public Function ConvertBack(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
            If TypeOf value Is Double OrElse TypeOf value Is Decimal Then
                Return value / 100
            Else
                Return 0
            End If
        End Function
    

    【讨论】:

    • 啊?? -1 愿意解释一下吗?
    猜你喜欢
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    • 2015-10-22
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 2011-11-01
    相关资源
    最近更新 更多