Wpf 如何格式化UI控件';s双数据值到数字,例如1234到1.23K?
如何使wpf UI控件(如TextBlock)以数字格式显示双值,例如: -如果双精度值为12345,则使其显示12.3K或12,3K -如果双精度值为123,则使其显示0,12K或0.12K 我试过StringFormat={}{0:#,}K},这不支持小数点后的2位数字 WPF文本块双值格式 Binding=“{Binding Volume,StringFormat={}{0:#,}K}” 期望: -12345为12.3K -123为0.12K ps:我已经尝试了IValueConverter解决方案。我的数据显示在datagrid控件中。使用IValueConverter。我会得到“12.3K”不正确的数据“12345”后,复制到剪贴板Wpf 如何格式化UI控件';s双数据值到数字,例如1234到1.23K?,wpf,string-formatting,Wpf,String Formatting,如何使wpf UI控件(如TextBlock)以数字格式显示双值,例如: -如果双精度值为12345,则使其显示12.3K或12,3K -如果双精度值为123,则使其显示0,12K或0.12K 我试过StringFormat={}{0:#,}K},这不支持小数点后的2位数字 WPF文本块双值格式 Binding=“{Binding Volume,StringFormat={}{0:#,}K}” 期望: -12345为12.3K -123为0.12K ps:我已经尝试了IValueConverte
我想我需要一种字符串格式的方式。使用绑定时可以使用转换器。创建转换器类:
public class DoubleFormatter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string formatedDouble = "";
formatedDouble = System.Convert.ToString(System.Convert.ToDouble(value) / 1000).Substring(0,4) + "K";
return formatedDouble;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
创建静态资源:
<local:DoubleFormatter x:Key="DoubletoKFormat"/>
然后像这样使用它:
<TextBlock Text="{Binding Header, Converter={ StaticResource DoubletoKFormat }}"/>
Hi LittleBit,我已经看过很多人了,但是如何让它在WPF UI控件上工作呢?然后你应该学习WPF中的Binding
s是如何工作的。网络上有很多教程(比如这样)将重复问题答案中的代码放入绑定转换器。嗨,克莱门斯,我知道IValueConverter解决方案。我的数据显示在datagrid控件中。通过使用IValueConverter,我将得到字符串“1.23K”在复制到剪贴板后不正确的数据“12345”。是的,我知道这一点。我的数据显示在数据网格中,如果我使用IValueConverter,我将在复制到剪贴板后获得字符串“1.23K”,而不是原始数据“12345”。