DelegateCommand<T>.ConvertParameter fails on int to int? conversion

Sep 16, 2011 at 7:47 PM
Edited Sep 16, 2011 at 8:11 PM

I have a project that I started around the first of the year.  I put it away, around the end of March, and worked on something else for several months and then came back to it.  The first thing I did was upgrade to the latest version of the Simple MVVM Toolkit.  Now I'm getting an error that I didn't get before.  The error is related to the "ConvertParameter" method in "GenericDelegateCommands.cs"  The "ConvertParameter" method throws an exception if the generic type T is a nullable type, like "int?".  object.GetType() returns the underlying value type, rather than a nullable type, so the line;

if(parameter != null & parameter.GetType == typeof(T))
{...}

will result in a "false" and it will eventually fall through to the exception.

Any help would be greatly appreciated.

Marty

 

Coordinator
Sep 16, 2011 at 8:20 PM
Can't remember if it supports nullable value types. I'll check and get back to you.

Cheers,
Tony
Sep 19, 2011 at 11:55 AM

Thanks Tony.  I've tried some experiments with things like;

T result = default(T);
if(parameter != null && result.GetType() == parameter.GetType())...

which would seem to work on the surface, but when you use a nullable type as T, result is null, which causes result.GetType() to fail.
I'm sure there must be a way, but I haven't seen it yet.

Thanks,

Marty

 

Sep 19, 2011 at 8:17 PM

Tony,

I've come up with a temporary solution.  If you come up with something better I'll be glad to use it.  Here's my hack;

            T result = default(T);
            if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>) &&
                parameter != null && typeof(T).ToString().Contains(parameter.GetType().ToString()))
            {
                    result = (T)parameter;
            }
            else if (parameter != null && parameter.GetType() == typeof(T))

This allows the cast from a non-nullable value type to a nullable value type, based on the fact that ToString() of the nullable type will contain the ToString() of the non-nullable type.  It's ugly, but it works, at least in my case.

Marty

Coordinator
Sep 21, 2011 at 1:44 PM

Hi Marty,

As you've discovered, type conversion with NVT's is problematic.  The CLR spoofs the NVT by returning the type arg of Nullable<T> from object.GetType.  Have you tried this?

T result = default(T);
if (parameter != null && parameter is T)
{
    result = (T)parameter;
}

How are you setting CommandParameter to a Nullable<T> in your XAML?  Are you using an attribute or property element syntax?

Cheers,

Tony