【问题标题】:Using WPF Binding StringFormat with literals both for input and output将 WPF Binding StringFormat 与文字一起用于输入和输出
【发布时间】: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

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    由于“12 pt”不是有效的double 值,默认转换器无法将其转换回double。所以是的,这确实只能单向工作。

    您应该使用自定义转换器,该转换器也知道如何将string 转换为double

    【讨论】:

    • 好的,这就是答案,尽管不完全是我所寻求的启示。该格式用于将源值转换为字符串,字符串通过默认转换器返回到 double。 StringFormat 不能双向工作的原因可能在于 .NET 本身 - 有 String.Format 但没有 String.Parse,因为格式化的字符串无法无损失地转换回 any 类型。它仍然适用于基本类型。
    猜你喜欢
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多