WPFUser
WPFUser

Reputation: 1185

CastException while using Decimal? type

in my scenario i need to bind Decimal? type property to Double? type property.

Here is the simple code using Double?

public class Model
    {
        private double? id = null;
        public double? ID
        {
            get { return id; }
            set { id = value;  }
        }
    }

and my Xaml

 <TextBox x:Name="db" Width="100"  Height="{Binding Path=ID}" />

this works without any issues, but if i change type of ID as Decimal? like,

 public class Model
    {
        private decimal? id = null;
        public decimal? ID
        {
            get { return id; }
            set { id = value;  }
        }
    }

it throws exception(need to enable all exception in VS). is there any specific reason behind this behavior ?

exception details :

System.InvalidCastException occurred _HResult=-2147467262
_message=Null object cannot be converted to a value type. HResult=-2147467262 IsTransient=false Message=Null object cannot be converted to a value type. Source=mscorlib StackTrace: at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) InnerException:

Thanks

Upvotes: 1

Views: 617

Answers (2)

Digifaktur
Digifaktur

Reputation: 257

So, the reason is what's written in the exception:

Null object cannot be converted to a value type

When it tries to make a double value (for the "Height" property) out of your decimal, the conversion method ("System.Convert.ChangeType") does not know how to deal with a null(able) value. Since this method never gets called when the type of the property ("double?") and the binding property ("ID") are of the same type, you never encounter this error in your original environment.

Upvotes: 1

iJay
iJay

Reputation: 4293

Add namespace xmlns:sys="clr-namespace:System;assembly=mscorlib"

And use this:

<TextBox x:Name="db" Width="100"  Height="{Binding ID, TargetNullValue={x:Static sys:String.Empty}}"/>

Upvotes: 1

Related Questions