Files
VacuumPressureMembranePoreS…/Converters/DoubleStringConverter.cs
2026-04-02 20:10:08 +08:00

40 lines
1.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Globalization;
using System.Windows.Data;
namespace MembranePoreTester.Converters
{
// 将 double 与 string 之间进行安全转换,避免在输入未完成时把值重置为 0
public class DoubleStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return string.Empty;
if (value is double d)
{
return d.ToString("G", culture);
}
return value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var s = (value as string) ?? string.Empty;
s = s.Trim();
if (string.IsNullOrEmpty(s))
{
// 不强制将空字符串写回为0避免用户输入时被覆盖
return Binding.DoNothing;
}
if (double.TryParse(s, NumberStyles.Any, culture, out double result))
{
return result;
}
// 如果解析失败,不更新源
return Binding.DoNothing;
}
}
}