2

I want to create a generic data type converter in my WPF application like this class template:

[ValueConversion(typeof(T), typeof(string))]
class DataTypeConverter<T> : IValueConverter

to convert data types like int, double, byte, ushort to string and vice versa and use it in two way bindings of different property types of my classess, and then simply create any type by this single line of code:

class ushortTypeConverter : DataTypeConverter<ushort>{}

and if possible shows validation message in textboxes that is bound in the case of wrong input.

Is it possible to write such a class template?

Naser Asadi
  • 1,153
  • 18
  • 35
  • Is typeof(T) in the attribute a placeholder (meaning change T to int, double etc) or a generic argument? Unfortunately, you cannot use generic attributes. See http://stackoverflow.com/questions/294216/why-does-c-sharp-forbid-generic-attribute-types for more information. – akton Jan 01 '13 at 12:23
  • I want to use it as generic argument, however this line of code: [ValueConversion(typeof(T), typeof(string))] is "[good practice](http://msdn.microsoft.com/en-us/library/system.windows.data.valueconversionattribute.aspx)" and can be omitted. – Naser Asadi Jan 01 '13 at 12:27

1 Answers1

5

Unfortunately, you cannot use generic attributes( typeof(T) in [ValueConversion(typeof(T), typeof(string))]. See Why does C# forbid generic attribute types? for more information. To paraphrase, it is a compiler simplification to avoid what was thought a rare edge case.

Apart from that, I cannot think of a reason why this approach would not work. However, there are classes like System.ComponentModel.TypeConverter that can probably do most of the conversion for you without the generics. Wrapping that in a simple converter may be easier.

Otherwise, there are a lot of IValueConverters out there that may do all or part of what you need. See:

Community
  • 1
  • 1
akton
  • 14,148
  • 3
  • 43
  • 47
  • Thanks for your comment akton. What about other parts of the problem without generic attribute? Is it possible? – Naser Asadi Jan 01 '13 at 12:33
  • I cannot see any immediate problems. however, as I expanded in my answer, I think it may be easier just to use TypeConverter instead. – akton Jan 01 '13 at 12:44
  • `Convert` method implementation could be as easy as `return value.ToString();` but `ConvertBack` method is more complicated beacuse generic parameter can't be categorized or constrainted to use something like `T.TryParse()`. – Naser Asadi Jan 01 '13 at 14:20
  • Agreed but look at System.Component.TypeConverter as I mentioned in the answer. It can do both directions generically for many types. – akton Jan 01 '13 at 14:24