条件 FormatString 或 String.Format

Posted

技术标签:

【中文标题】条件 FormatString 或 String.Format【英文标题】:Conditional FormatString or String.Format 【发布时间】:2010-12-31 22:25:00 【问题描述】:

我看到了这个帖子: How to Conditionally Format a String in .Net?

问题的第一部分指出了使用条件格式的能力。这是怎么做到的?

就我而言,例如,我想将 100,000 设为 10 万美元,将 1,000,000 设为 100 万美元。我希望能够仅使用标记中的 FormatString (Silverlight)来做到这一点。这是我无法使用值转换器的情况(它在样式中)。

这可能吗?

【问题讨论】:

你需要自己编码。签出:***.com/questions/2134161/… 在我链接到的那篇文章中这是指什么? Int32 我 = 0; i.ToString("$#,##0.00;($#,##0.00);零"); 【参考方案1】:

您可以实现自己的IFormatProvider 并定义 ie。自定义并在调用 String.Format()ToString() 时传递它。

可以在此处http://msdn.microsoft.com/en-us/library/system.iformatprovider.aspx 或此处http://www.codeproject.com/KB/cs/custstrformat.aspx 找到此示例。

public class StringFormatInfo : IFormatProvider, ICustomFormatter

   ...


return number.ToString("0:custom", new StringFormatInfo());

【讨论】:

我自己用过很多次......它是一个干净漂亮的 api,而不是使用各种辅助方法。 我认为这不是我的选择,因为我使用的是模板绑定。我需要在应用于图表轴上的标签的样式中(Silverlight Toolkit)。我试试看。 这里有一篇文章是关于如何在WPF中进行数据绑定时使用自定义IFormatProvider的timheuer.com/blog/archive/2008/07/30/…

以上是关于条件 FormatString 或 String.Format的主要内容,如果未能解决你的问题,请参考以下文章

javascript Gatsby / GraphQL - formatString日期字段

string.format的参数

Express.js - Mongoose 多个或条件

Go语言的各种Print函数

shell-条件测试

如何用 if 条件填充列