在WPF中使用TextBox我遇到的问题是,如果我使用','而不是'。'每次我尝试获取值时,TextBox内的文本都使用相同的数字进行转换而不使用逗号..
如何禁用此自动转换?
<TextBox
x:Name="XValue"
Text="{Binding XInitValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Width="80" VerticalAlignment="Center"
TextChanged="XValue_TextChanged"
</TextBox>
private void XValue_TextChanged(object sender, TextChangedEventArgs e)
{
double a = XInitValue;
}
答案 0 :(得分:0)
我使用转换器解决了它
public class DecimalConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator == ".")
return value.ToString().Replace(",", ".");
else
return value.ToString().Replace(".", ",");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator == ".")
return value.ToString().Replace(".", ",");
else
return value.ToString().Replace(",", ".");
}
}
答案 1 :(得分:0)
它确实有效!谢谢!
我将其更改为更通用一些,不要在转换器本身中使用CurrentCulture,如果输入的值以小数点分隔符结尾,则会返回错误。没有最后一部分,如果UpdateSourceTrigger = PropertyChanged,我根本无法输入小数点分隔符。
public class DecimalConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return null;
}
if (value is string stringValue && targetType == typeof(decimal))
{
var decSeparator = culture.NumberFormat.NumberDecimalSeparator;
var normString = decSeparator == "."
? stringValue.Replace(",", ".")
: stringValue.Replace(".", ",");
if (!normString.EndsWith(decSeparator) && decimal.TryParse(normString, out var decResult))
{
return decResult;
}
}
return DependencyProperty.UnsetValue;
}
}
当然应该在App.xml.cs或启动应用程序的其他地方设置CurrentCulture:
var culture = CultureInfo.GetCultureInfo("de-DE");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
FrameworkElement.LanguageProperty.OverrideMetadata(
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
XmlLanguage.GetLanguage(culture.IetfLanguageTag)));