如果我有这样的TextBox:
<TextBox Text="{Binding Voltage, StringFormat={}{0} kV}" />
和属性电压是例如50,我在TextBox中得到“50 kV”。这就是我的意图。
但是现在,如果用户想要输入一个新值40并键入“40 kV”,他会得到一个红色边框,因为有一个FormatException转换回来的值。
System.Windows.Data Error: 7 : ConvertBack cannot convert value '40 kV' (type 'String'). BindingExpression:Path=Voltage; DataItem='VMO_VoltageDefinition' (HashCode=19837180); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') FormatException:'System.FormatException: Die Eingabezeichenfolge hat das falsche Format.
我不认为我的程序的用户会接受这个。
我做错了什么,或者这个功能是否与TextBox合理使用?
答案 0 :(得分:2)
我建议使用转换器:
<TextBox Text="{Binding Voltage, Converter={StaticResource VoltageToString}}" />
其中:
<Window.Resources>
<mstf:VoltageToStringx:Key="VoltageToString" />
</Window.Resources>
代码隐藏:
public class VoltageToString: IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return ((int)value).ToString() + " kV";
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return int.Parse((string).Replace(" kV",""));
}
}
这只是一个基本的例子,但你应该知道如何使它更复杂。
答案 1 :(得分:1)
StringFormat
是Binding
标记扩展的属性,理论上可用于任何绑定。但是,大多数情况下仅使用单向绑定才有意义。
你是对的,在TextBox中,stringformat没有多大意义。
你可以像David建议的那样通过转换器解决它,但我建议你在TextBox外的TextBlock中显示单位:
<DockPanel>
<TextBlock Text="kV" DockPanel.Dock="Right />
<TextBox Text="{Binding Voltage}" />
</DockPanel>
这种感觉更自然,并提供更好的用户体验。
或者,您可以使用名为Unit或Description的新属性或其他任何内容创建从TextBox派生的自定义控件,并修改控件模板,以便显示单元。然后最终的标记可能如下所示:
<my:TextBox Text="{Binding Voltage}" Description="kV" />