且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自定义的WinForms数据转换器不工作的空类型绑定(双?)

更新时间:2023-01-01 09:56:15

其实,这个错误并不在code,但在一个你已经下载(CustomBinding $ C $ C>)。修改构造成为

In fact, the bug is not in your code, but in the one you have downloaded (CustomBinding). Modify constructors to become

public CustomBinding(string propertyName, object dataSource, string dataMember, IValueConverter valueConverter, object converterParameter = null)
    : this(propertyName, dataSource, dataMember, valueConverter, Thread.CurrentThread.CurrentUICulture, converterParameter)
{ }

public CustomBinding(string propertyName, object dataSource, string dataMember, IValueConverter valueConverter, CultureInfo culture, object converterParameter = null)
    : base(propertyName, dataSource, dataMember, true)
{
    this._converter = valueConverter;
    this._converterCulture = culture;
    this._converterParameter = converterParameter;
}

和问题将得到解决。的重要组成部分是,​​ Binding.FormatingEnabled 必须为了这一切工作(注意,最后一个参数基地电话,但你可以在以后将它设置得)。另请注意,我删除了

and the problem will be solved. The essential part is that Binding.FormatingEnabled must be true in order all this to work (note the last argument to the base call, but you can set it later too). Also note that I removed

this.DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged;

行。它的默认值是 OnValidation 这是适用于任何控制权。 OnPropertyChanged 适用于像复选框,单选按钮和非可编辑组合框即时更新控制。在任何情况下,***是离开这个属性设置为该类用户的责任。

line. The default value for this is OnValidation which is applicable for any control. OnPropertyChanged is applicable for immediate update controls like check boxes, radio buttons and non editable combo boxes. In any case, it is better to leave the responsibility of setting this property to the user of the class.

一个侧面说明无关的问题:你***关闭没有剥离无效字符,让例外,你的 ConvertBack 方法中被抛出,否则,你得到一个奇怪的输入值,如果如用户键入1-3

A side note unrelated to the question: You'd better off not stripping the invalid characters and let the exception to be thrown inside your ConvertBack method, otherwise you get a weird input values if the user types for instance "1-3"

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    var text = value != null ? ((string)value).Trim() : null;
    return !string.IsNullOrEmpty(text) ? (object)double.Parse(text, NumberStyles.Any, culture) : null;
}