Custom WinForms data binding with converter not working on nullable type (double?)

前端 未结 1 1732
一向
一向 2021-01-28 07:25

In my WinForms application I implemented custom data binding with support for value converters, similar to WPF.

The sample has a new binding class that derives from

1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-28 08:01

    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;
    }
    

    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;
    

    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.

    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;
    }
    

    0 讨论(0)
提交回复
热议问题