Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF binding with explicit conversion

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.

like image 543
Tri Q Tran Avatar asked Mar 01 '23 01:03

Tri Q Tran


1 Answers

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.

like image 153
Paul Stovell Avatar answered Mar 04 '23 11:03

Paul Stovell