我开发工程应用程序,因此不断处理双
数字。作为新手,由于 ComboBox 和其他控件更喜欢字符串,因此我的模型是基于字符串的:
Diameter = "0.523";
我已经进行了 Google 搜索,并获得了一些有关转换器的初步(令人困惑、矛盾的)信息:需要一个统一的解释。
IValueConverter
接口(interface)建立了一个 Convert()
和一个 ConvertBack()
对,但是每个的方向是什么?转换器是绑定(bind)到 TextBox
的 XAML,而我的模型处理 double
。 Convert()
半幕是从 TextBox
中出还是进入其中?
我的目标是在输入非法数字时形成的红色矩形附近添加警告:“您输入的 float 格式不正确”。
我编写了 2 个转换器类:DoubleToString
和 StringToDouble
。不确定哪一个是正确的(另外,两者都崩溃了)。
最佳答案
大多数时候,人们只在工作中使用 Convert 方法。 ConvertBack用于双方都需要转换的情况。 XAML 到模型,反之亦然
这是 double 的示例。您可以根据需要进一步格式化该值。
[ValueConversion(typeof(double) ,typeof(string))]
public class DoubleConverter : IValueConverter
{
public object Convert(object value ,Type targetType ,object parameter ,CultureInfo culture)
{
double doubleType = (double)value;
return doubleType.ToString();
}
public object ConvertBack(object value ,Type targetType ,object parameter ,CultureInfo culture)
{
string strValue = value as string;
double resultDouble;
if ( double.TryParse(strValue ,out resultDouble) )
{
return resultDouble;
}
return DependencyProperty.UnsetValue;
}
}
关于c# - 需要帮助开发和绑定(bind) Double <--> 转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20598799/