Winforms data binding: Can a TypeConverter be used instead of the Format/Parse events?

后端 未结 2 651
余生分开走
余生分开走 2021-01-18 05:41

In a Winforms form, I want to provide visual cues to the user when an input field contains an invalid value. To that end, I want to bind the ForeColor property

2条回答
  •  生来不讨喜
    2021-01-18 06:22

    My previous answer (now deleted) was incorrect: This can be done, using a custom TypeConverter.

    First, one needs a suitable converter. (Unlike with XAML, one does not implement a IValueConverter, but derive from TypeConverter.) For example:

    // using System;
    // using System.ComponentModel;
    // using System.Drawing;
    // using System.Globalization;
    
    sealed class BooleanToColorConverter : TypeConverter
    {
        public override bool CanConvertTo(ITypeDescriptorContext context,
                                          Type destinationType)
        {
            return destinationType == typeof(Color);
        }
    
        public override object ConvertTo(ITypeDescriptorContext context,
                                         CultureInfo culture,
                                         object value, 
                                         Type destinationType)
        {
            return (bool)value ? Color.Green : Color.Red;
        }
    }
    

    Next, (and also unlike with XAML data binding,) this converter is not applied to the binding itself; it must be attached to the data source's property using the [TypeConverter] attribute:

    // using System.ComponentModel;
    
    partial class DataSource : INotifyPropertyChanged
    {
        [TypeConverter(typeof(BooleanToColorConverter))] // <-- add this! 
        public bool IsValid { get { … } set { … } }
    }
    

    Finally, formatting must be enabled on the data binding:

    // Control control = …;
    // DataSource dataSource = …;
    
    control.DataBindings.Add("ForeColor", dataSource, "IsValid", formattingEnabled: true);
    //                                                           ^^^^^^^^^^^^^^^^^^^^^^^
    

    Note that this example only deals with one-way (data source to control) data binding. For two-way data binding, you would additionally have to override the TypeConverter.ConvertFrom and TypeConverter.CanConvertFrom methods.

提交回复
热议问题