Daa*_*nvl 3 c# wpf datagrid string-formatting
快(我希望)问题.我有这个DataGrid,包含一些货币列.我似乎无法找到的是如何以2位小数显示货币.但是在单元格中保持可能的3或4十进制值.如果尝试了一些字符串格式,但实际上会更改值.当然,IValueConverter也是如此.那我错过了什么?或者有人能指出我正确的方向吗?
编辑:在建议后我尝试了这样的事情.
<Style x:Key="DecimalTextBlockStyle" TargetType="{x:Type DataGridCell}">
<Setter Property="TextBlock.Text" Value="{Binding StringFormat={}{0:C}}"/>
<Setter Property="TextBlock.Foreground" Value="Red"/>
<Setter Property="Background" Value="AliceBlue"/>
</Style>
Run Code Online (Sandbox Code Playgroud)
并在这里申请:
if(e.PropertyType.FullName.Contains("Decimal"))
{
var cl = e.Column as DataGridTextColumn;
if (cl != null)
{
//cl.Binding.StringFormat = "C2";
Style Stl = (Style)FindResource("DecimalTextBlockStyle");
cl.CellStyle = Stl;
}}
Run Code Online (Sandbox Code Playgroud)
但我没有得到的是为什么!这些列中的值是漂亮的红色文本,蓝色背景..但是未格式化的字符串,只显示0,000而不是€0,00
使用StringFormat或单向Converter不应改变实际值.这两者仅用于显示目的.
例如,这将以货币格式显示带有2位小数的十进制值,但不会修剪SomeDecimal为两位小数
<TextBox Text="{Binding SomeDecimal, StringFormat=C2}" />
Run Code Online (Sandbox Code Playgroud)
也许您希望使用2位数显示值,但使用完整的4位数进行编辑.如果是这种情况,我建议使用样式触发器在编辑时显示未格式化的值.
<Style x:Key="DecimalTextBoxStyle" TargetType="{x:Type TextBox}">
<Setter Property="Text" Value="{Binding SomeDecimal, StringFormat=C2}" />
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="Text" Value="{Binding SomeDecimal}" />
</Trigger>
</Style.Triggers>
</Style>
Run Code Online (Sandbox Code Playgroud)
编辑
根据下面的请求将此样式应用于a DataGridCell,您可以使用a DataGridTemplateColumn并在其中放置TextBox并应用此样式,或者您可以使用ElementStyle和EditingElementStyle属性设置绑定格式
<DataGridTextColumn>
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Text" Value="{Binding SomeDecimal, StringFormat=C2}" />
</Style>
</DataGridTextColumn.ElementStyle>
<DataGridTextColumn.EditingElementStyle>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Text" Value="{Binding SomeDecimal}" />
</Style>
</DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>
Run Code Online (Sandbox Code Playgroud)