views:

248

answers:

2

Hello everyone,

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.

+1  A: 

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.

Paul Stovell
Thank you Paul. Could you also link me the the generic helper methods you are talking about?
Tri Q
A: 

No, WPF will not call the implicit converter. You must use a value converter or Paul's TypeConverter suggestion.

itowlson