我需要格式化布尔值作为多语言支持“Ja”/“Nein”的字符串。女巫是我需要DisplayFormat和EditFormat的正确格式字符串吗? 我使用DevExpress和repositoryItemTextEdit作为设计中的列编辑器,但我认为它与任何其他绑定字符串格式相同。还有另一种方法吗?自定义字符串格式
Q
自定义字符串格式
1
A
回答
4
您应该将字面值“Ja”/“Nein”提取到本地化资源中。 老人作出了很好的回应,但我会用一些例子来扩展它。
首先,定义自定义格式提供,将使用定位在某种
public class LocalizedBoolFormatter : IFormatProvider, ICustomFormatter
{
public string Format(string format, object arg, IFormatProvider formatProvider)
{
bool value = (bool)arg;
format = (format == null ? null : format.Trim().ToLower());
switch (format)
{
case "yn":
return GetLocalizedBool(value);
default:
return HandleDefaultFormat(arg, format, formatProvider);
}
}
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
}
为LocalizedBoolFormatter
私有方法可能如下:
private string HandleDefaultFormat(object value, string format, IFormatProvider formatProvider)
{
if (value is IFormattable)
return ((IFormattable)value).ToString(format, formatProvider);
else
return value.ToString();
}
private string GetLocalizedBool(bool value)
{
//extract from localization resources
//or use CultureInfo.CurrentCulture for poors man localization
return value ? "Ja" : "Nein";
}
然后,你可以简单地使用自定义格式器格式值,其将由格式化器本地化
bool f = false;
string formatted = string.Format(new LocalizedBoolFormatter(), "{0:yn}", f);
Console.WriteLine (formatted);
W第i个DevExpress的RepositoryItemTextEdit可以使用Custom Formatting如下:
repositoryItemTextEdit.DisplayFormat.Format = new LocalizedBoolFormatter();
repositoryItemTextEdit.DisplayFormat.FormatType = FormatType.Custom;
3
布尔值不能自动转换为当前语言环境。你可以使用一个扩展方法将其转化:
public static string ToPrettyString(this bool value) {
return value ? YourResource.TrueValue : YourResource.FalseValue;
}
如果您需要更多的灵活性,检查答案Boolean Format String - Yes/No instead of True/False那里,也可以实现IFormatProvider
的例子。
1
的easyest的方法是使用一个不同的属性或列的格式化值。 您还可以使用数据绑定的分析/格式事件:
repositoryItemTextEdit1.DataBindings[0].Format += new ConvertEventHandler(repositoryItemTextEdit1_Format);
repositoryItemTextEdit1.DataBindings[0].Parse += new ConvertEventHandler(repositoryItemTextEdit1_Parse);
void repositoryItemTextEdit1_Format(object sender, ConvertEventArgs e)
{
return e.Value ? "Ja" : "Nein";
}
void repositoryItemTextEdit1_Parse(object sender, ConvertEventArgs e)
{
return e.Value.Equals("Ja") ? yes : no;
}
相关问题
- 1. 字典自定义字符串格式
- 2. 自定义字符串格式
- 3. 字符串格式自定义参数
- 4. Swift3从自定义格式字符串
- 5. 自定义PHP字符串格式
- 6. 自定义格式字符串
- 7. 格式字符串数组到自定义字符串
- 8. C#字符串字段的自定义显示格式
- 9. 支护的ToString(字符串格式)与自定义数字型
- 10. python:字典到字符串,自定义格式?只有
- 11. 检查自定义字符串模式
- 12. Excel自定义格式,检查字符
- 13. 结合自定义数字格式字符串与十六进制格式字符串
- 14. C#中的自定义字符串格式化程序#
- 15. 自定义字符串格式:的ToString( “00”)
- 16. 将自定义集合字符串转换为JSON格式
- 17. 时间戳与自定义格式的字符串
- 18. JavaScript字符串使用自定义格式
- 19. 自定义字符串格式0,0斜杠或反斜杠
- 20. Bukkit /插口HeroChat 5:在格式字符串自定义更换
- 21. 使用自定义格式序列化JSON字符串
- 22. Grails中的自定义字符串格式JSON编组
- 23. 对象列表的自定义字符串格式
- 24. 转换自定义字符串,日期时间格式
- 25. 字符串格式自定义的方法扩展
- 26. 自定义格式字符串不显示0
- 27. C#自定义OCR,返回一个格式化的字符串
- 28. WPF字符串格式使用自定义分隔
- 29. 如何使用字符串写入自定义日期格式?
- 30. JAVA - 使用SimpleDateFormat格式化自定义字符串