【发布时间】:2011-01-27 11:32:06
【问题描述】:
如果我将 TextBox 中的 Text 绑定到 float 属性,则显示的文本不支持系统小数点(点或逗号)。相反,它总是显示一个点 ('.')。但如果我在 MessageBox 中显示值(使用 ToString()),则使用正确的系统十进制。
Xaml
<StackPanel>
<TextBox Name="floatTextBox"
Text="{Binding FloatValue}"
Width="75"
Height="23"
HorizontalAlignment="Left"/>
<Button Name="displayValueButton"
Content="Display value"
Width="75"
Height="23"
HorizontalAlignment="Left"
Click="displayValueButton_Click"/>
</StackPanel>
背后的代码
public MainWindow()
{
InitializeComponent();
FloatValue = 1.234f;
this.DataContext = this;
}
public float FloatValue
{
get;
set;
}
private void displayValueButton_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(FloatValue.ToString());
}
到目前为止,我已经用一个转换器解决了这个问题,该转换器用系统十进制替换 dot (有效),但这是必要的原因是什么?这是设计使然吗?有没有更简单的方法来解决这个问题?
SystemDecimalConverter(以防其他人遇到同样的问题)
public class SystemDecimalConverter : IValueConverter
{
private char m_systemDecimal = '#';
public SystemDecimalConverter()
{
m_systemDecimal = GetSystemDecimal();
}
object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.ToString().Replace('.', m_systemDecimal);
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.ToString().Replace(m_systemDecimal, '.');
}
public static char GetSystemDecimal()
{
return string.Format("{0}", 1.1f)[1];
}
}
【问题讨论】:
标签: c# wpf textbox wpf-controls culture