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