40 lines
1.2 KiB
C#
40 lines
1.2 KiB
C#
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;
|
||
}
|
||
}
|
||
}
|