views:

69

answers:

1

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?

+3  A: 

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);
        }
    }
}
Marc Gravell
I was thinking more along the lines of having members/properties (which already have validation attributes) that I could also apply some sort of attribute to control formatting. This would include built in types like double, etc.
user144182
@user144182 - isn't that exactly what I've shown? A property (`SomeValue`), with an attribute (`[TypeConverter]`) to assist in formatting, which handles a built-in type (`decimal`)
Marc Gravell
Sorry Marc, I wasn't clear - I was thinking along the lines of perhaps being able to specify a format string in the attribute itself, say something like [DataFormat(0.00)].
user144182
@user144182 To do that, you would have to write a `TypeConverter` that investigated the `context` parameter to look at the `PropertyInfo`, checking for additional attributes. Nothing built in otherwise. Some bindings support formatting like this via `IFormattable`, though.
Marc Gravell
What about making MyConverter have a constructor that accepts a .NET format string and then have ConvertTo use that string while converting?
user144182
That won't get used - all you specify is the `typeof` - not the constructor overload (unless you go to a *lot* more trouble, involving `ICustomTypeDescriptor` and `PropertyDescriptor.Converter`).
Marc Gravell