【发布时间】:2017-03-30 10:34:04
【问题描述】:
我在 WPF 桌面应用程序 UI 中有一个字体点大小选择器。我以前在这种情况下使用过转换器,这也可能是这里的方法。
但是,我可以在绑定中使用 StringFormat,它看起来更简单(避免创建转换器)。它适用于数值,但似乎我无法将文字添加到如下格式:StringFormat='{}{0:N} pt'
在 XAML 中:
<ComboBox Text="{Binding SampleFontSize, StringFormat='{}{0:N} pt', ValidatesOnDataErrors=True" IsEditable="True">
<ComboBoxItem>8</ComboBoxItem>
<ComboBoxItem>10</ComboBoxItem>
<ComboBoxItem>12</ComboBoxItem>
<ComboBoxItem>14</ComboBoxItem>
注意 IsEditable=true
这将在我的语言环境中显示“12,00 pt”,但是当我输入完全相同的值时,它将触发验证错误:
System.Windows.Data Error: 7 : ConvertBack cannot convert value '12 pt' (type 'String'). BindingExpression:Path=SampleFontSize; DataItem='AnalysisSettingsViewModel' (HashCode=47173034); target element is 'ComboBox' (Name=''); target property is 'Text' (type 'String') FormatException:'System.FormatException: Input string was not in a correct format.
at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)
at System.String.System.IConvertible.ToDouble(IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at MS.Internal.Data.SystemConvertConverter.ConvertBack(Object o, Type type, Object parameter, CultureInfo culture)
at System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)'
我应该得出结论,带有文字的 StringFormat 只能以一种方式工作,还是我使用了不正确的 StringFormat? StringFormat={}{0:N} 工作正常,但 StringFormat={}{0:N} pt
【问题讨论】: