我有一个DataGrid
带有数字列的 WPF,这些列最初格式化为不带小数。
用户有一个复选框来选择数字格式以显示 0 或 2 个小数位。下面显示了该列的 xaml。
<DataGridTemplateColumn Header="Qty" Width="40" IsReadOnly="False" CellStyle="{StaticResource EditCell}">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding ItemQuantity, StringFormat={}{0:#}}" TextAlignment="Right" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox x:Name="textbox" BorderThickness="0" HorizontalContentAlignment="Right" Background="LightYellow">
<Binding Path="ItemQuantity" StringFormat="N0" UpdateSourceTrigger="LostFocus" >
<Binding.ValidationRules>
<c:DecimalRangeRule Min="0" Max="999999.99"/>
</Binding.ValidationRules>
</Binding>
</TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
StringFormat
更改复选框时如何更改列设置?
编辑:解决方案
我使用 MultiConverter(由 nit 建议)根据是否选中复选框来选择格式:
//==========================================================================
public class NumericFormatConverter : IMultiValueConverter
{
private const string FormatN0 = "{0:#,##0;-#,##0; }";
private const string FormatN2 = "{0:#,##0.00;-#,##0.00; }";
public object Convert( object[] values, Type targetType, object parameter, CultureInfo culture )
{
if ( values[0] == null ) return string.Empty;
decimal num = 0;
Decimal.TryParse( values[0].ToString(), out num );
string format = FormatN0;
bool isSmallValue = (values[1] == null ? false : (bool)values[1]);
if ( isSmallValue ) format = FormatN2;
return String.Format( format, num );
}
public object[] ConvertBack( object value, Type[] targetTypes, object parameter, CultureInfo culture )
{
decimal num = 0;
Decimal.TryParse( value.ToString(), out num );
object[] objects = new object[1] {num};
return objects;
}
}
DataGridTemplateColumn 更改为使用 MultiBinding:
<DataGridTemplateColumn Header="Qty" Width="40" IsReadOnly="False" CellStyle="{StaticResource EditCell}">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock HorizontalAlignment="Right" >
<TextBlock.Text>
<MultiBinding Converter="{StaticResource NumericFormat}">
<Binding Path="GroupQuantity" />
<Binding ElementName="chkSmallValue" Path="IsChecked"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox x:Name="textbox" BorderThickness="0" HorizontalContentAlignment="Right" Background="LemonChiffon" PreviewTextInput="TextBox_PreviewTextInput" >
<MultiBinding Converter="{StaticResource NumericFormat}" UpdateSourceTrigger="LostFocus">
<Binding Path="GroupQuantity" />
<Binding ElementName="chkSmallValue" Path="IsChecked" Mode="OneWay"/>
</MultiBinding>
</TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>