My question may be a repeat of other conversion question but I feel mine is different.
Here goes... [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 call the Implicit
and Explicit
converter in my DataWrapper<T>
class instead of needing to implement a IValueConverter
for each TextBlock
.
I can't say whether it would work or not, as I haven't tested it. However, if it doesn't work, you can try using a TypeConverter
for your DataWrapper
type.
For example:
[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 generic helper methods on the Type class to deal with your type conversion more dynamically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With