开发者

Attribute to specify display format of a property or field

I currently already decorate properties in my business objects with attributes related to validation in Windows Forms.

I would like to add attributes that 开发者_运维技巧would determine how the data is formatted. This would hopefully work seamlessly with data binding.

Is there a way to do this?


Formatting is achieved (in winforms) via two primary approaches:

  • for coarse-grained formatting, override ToString()
  • for fine-grained formatting, define a TypeConverter subclass, and use [TypeConverter(...)] on your custom type (or properties of a class, etc), to apply your formatting (when the target type is typeof(string))

For example:

using System;
using System.ComponentModel;
using System.Windows.Forms;
class MyObject
{
    [TypeConverter(typeof(MyConverter))]
    public decimal SomeValue { get; set; }
}

class MyConverter : TypeConverter {
    public override object  ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType)
    {
        if(destinationType == typeof(string)) {
            return "Our survery says: " + value + "%";
        }
         return base.ConvertTo(context, culture, value, destinationType);
    }
}
static class Program {
    [STAThread]
    static void Main() {
        using(var form = new Form()) {
            form.DataBindings.Add("Text",new MyObject { SomeValue = 27.1M}, "SomeValue", true);
            Application.Run(form);
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜