Associate WPF with explicit conversion

My question may be a repetition of another conversion question, but I feel that I have different ones.

Here ... [simplified example].

public class DataWrapper<T> { public T DataValue{ get; set; } public DataWrapper(T value) { DataValue = value; } public static explicit operator DataWrapper<T> (T value) { return new DataWrapper<T>(value); } public static implicit operator T(DataWrapper<T> data) { return data.DataValue; } } 

Now, in my ViewModel:

 public class ViewModel { public DataWrapper<string> FirstName { get;set; } public DataWrapper<string> LastName { get; set; } } 

And in XAML:

 <TextBlock Text="{Binding FirstName}" /> <TextBlock Text="{Binding LastName}" /> 

My question is: will this work? Will WPF binding invoke the Implicit and Explicit converter in my DataWrapper<T> class instead of having to implement an IValueConverter for each TextBlock .

+4
source share
2 answers

I can’t say whether this will work or not, since I have not tested it. However, if it does not work, you can try using TypeConverter for your DataWrapper type.

For instance:

 [TypeConverter(typeof(DataWrapperConverter))] public class DataWrapper { ... } public class DataWrapperConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value is string) { return (DataWrapper<string>)value; } return base.ConvertFrom(context, culture, value); } } 

You can use the general helper methods of the Type class to more dynamically convert your type.

+5
source

No, WPF will not invoke an implicit converter. You must use the value converter or the Paul TypeConverter clause.

+1
source

All Articles