【发布时间】:2018-12-24 11:34:45
【问题描述】:
我在 WPF 和 C# 中工作,遇到了一个我认为源于我的转换器的问题。我有一个文本框,在页面加载时,一个 INT 被转换为一个 DOUBLE 并显示出来。 示例:
- 初始值:32.99
- 可以更改为:
- 24
- 24.99
- 24.9
- 无法更改为:
- 24.09
在我输入 24.0 后会发生什么,它立即恢复为 24。我可以通过输入 24.9 然后在需要的位置输入 0 来实现 24.09。我试图弄乱我的转换器,认为这是我何时/如何将其转换为双精度的问题,但它仍然产生相同的结果。
这是转换器的代码:
//This takes in an int and converts it to a double with two decimal places
[ValueConversion(typeof(object), typeof(double))]
public class conDouble : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double db = System.Convert.ToDouble(value);
return (db / 100.00).ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return System.Convert.ToInt32((System.Convert.ToDouble(value) * 100));
}
}
正则表达式有问题的文本框:
<Page.Resources>
<system:String x:Key="regexDouble">^\d+(\.\d{1,2})?$</system:String>
</Page.Resources>
<TextBox Name="txtItemPrice" Grid.Column="12" Grid.ColumnSpan="2" Grid.Row="4" HorizontalAlignment="Stretch" VerticalAlignment="Center" IsEnabled="False"
Validation.ErrorTemplate="{StaticResource validationTemplate}"
Style="{StaticResource textStyleTextBox}">
<TextBox.Text>
<Binding Path="intPrice" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay" Converter="{StaticResource Double}">
<Binding.ValidationRules>
<classobjects:RegexValidation Expression="{StaticResource regexDouble}"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
最后是我的验证器:
public class RegexValidation : ValidationRule
{
private string pattern;
private Regex regex;
public string Expression
{
get { return pattern; }
set
{
pattern = value;
regex = new Regex(pattern, RegexOptions.IgnoreCase);
}
}
public RegexValidation() { }
public override ValidationResult Validate(object value, CultureInfo ultureInfo)
{
if (value == null || !regex.IsMatch(value.ToString()))
{
return new ValidationResult(false, "Illegal Characters");
}
else
{
return new ValidationResult(true, null);
}
}
}
【问题讨论】:
-
“这接受一个 int 并将其转换为带两位小数的双精度数” 不存在带有两位小数的双精度数。如果有小数位,它是一个字符串;双精度数始终是二进制的,并且相对于它们的字符串表示是中性的。
-
哦,好吧!谢谢你,这有助于我走上正确的道路!