我正在尝试格式化datagrid数据单元中的数字,以使'1000000.52'看起来像:'1 000 000.52'。
我试图寻找能够启用此类功能的属性,并且只能在 DataGridCell 类内找到 ContentStringFormat 属性。不幸的是,我尝试的方法不起作用:
<DataGrid CanUserAddRows="False" Name="EGrid" Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="2" ItemsSource="{Binding Path=Data, Mode=TwoWay, ElementName=ExportableGrid}">
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="ContentStringFormat" Value="## ### ###.00"/>
</Style>
</DataGrid.CellStyle>
</DataGrid>
我该如何实现?非常感谢您的任何帮助。
答案 0 :(得分:2)
我将创建一个自定义值转换器:
Imports System.Globalization
Public Class DecimalFormatConverter
Implements IValueConverter
Public Function IValueConverter_Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
Dim decimalVal As Decimal = Nothing
If value IsNot Nothing AndAlso parameter IsNot Nothing AndAlso Decimal.TryParse(value.ToString(), decimalVal) Then
Return decimalVal.ToString(parameter.ToString())
End If
Return value
End Function
Public Function IValueConverter_ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
Throw New NotImplementedException
End Function
End Class
要在xaml中使用它,
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp6VB"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
<Grid>
<Grid.Resources>
<local:DecimalFormatConverter x:Key="DecimalFormatConverter" />
</Grid.Resources>
<DataGrid CanUserAddRows="False" x:Name="EGrid" Grid.Column="0" ItemsSource="{Binding Nums}" >
<DataGrid.Columns>
<DataGridTemplateColumn Header="Number">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource DecimalFormatConverter}, ConverterParameter='## ### ###.00'}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
输出:
答案 1 :(得分:0)
您需要将其转换为字符串,将其拆分并在需要的地方添加空格。
我对您的问题进行了硬编码。
如果您希望代码段使用不同的数字,建议您使用相同的逻辑并在数字长度上创建一个Select/Case
。
这是解决您的问题的代码:
Dim number As Double = 1000000.52
Dim str() As String = Convert.ToString(number).Split(",")
str(0) = "" & _
str(0).Substring(0, 1) & _
" " & str(0).Substring(1, 3) & _
" " & str(0).Substring(4, 3) & _
"." & str(1)