【问题标题】:Using a Custom format with binding source?使用带有绑定源的自定义格式?
【发布时间】:2016-06-09 18:15:03
【问题描述】:

我有许多类都有一个字符串属性来保存IBAN

出于显示目的,我想在每 4 个字符后用一个空格显示该值,例如:

'GB29 NWBK 6016 1331 9268 19'

是否可以编写一个实现ICustomFormatter 的类,然后为文本框数据绑定指定这种新的自定义格式?

或者处理BindingSourceBindingComplete 事件会更好吗?

【问题讨论】:

  • 如何在字符串上编写一个扩展方法,返回格式化字符串?所以该方法将类似于字符串上的 ToIBAN()
  • @Dheeraj 扩展很容易编写,但我需要处理 Parse 和 Format 事件,而不是设置 {0:I} 之类的东西,其中 I 是格式字符串
  • 使用MaskedTextBox 进行显示怎么样?

标签: c# winforms data-binding


【解决方案1】:

一般方法是将自定义TypeConverter 与该类型的类属性相关联。

例如:

格式化程序:

public static class IBAN
{
    public static string Format(string value)
    {
        if (string.IsNullOrEmpty(value)) return value;
        var sb = new StringBuilder();
        for (int i = 0; i < value.Length; i++)
            (i != 0 && (i % 4) == 0 ? sb.Append(' ') : sb).Append(value[i]);
        return sb.ToString();
    }
}

转换器:

public class IBANTypeConverter : TypeConverter
{
    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string))
            return IBAN.Format(value as string);
        return base.ConvertTo(context, culture, value, destinationType);
    }
}

具有属性的示例数据类:

public class MyObject
{
    [TypeConverter(typeof(IBANTypeConverter))]
    public string IBAN { get; set; }
}

示例数据绑定:

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        var data = new MyObject { IBAN = "GB29NWBK60161331926819" };
        var form = new Form();
        var tbIBAN = new TextBox { Parent = form, Left = 8, Top = 8, Width = form.ClientSize.Width - 16, Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right };
        tbIBAN.DataBindings.Add("Text", data, "IBAN", true);
        Application.Run(form);
    }
}

【讨论】:

  • 文本框获得焦点时是否可以“取消格式化”字符串?
  • 恐怕不行,除非你使用支持它的特殊控件。数据绑定只支持格式化和解析。
猜你喜欢
  • 2017-01-02
  • 2013-08-11
  • 2011-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多