【发布时间】:2010-12-11 01:12:48
【问题描述】:
我们有一个自定义控件,它具有 System.Nullable 类型的“Value”属性(又名 System.DateTime?)。我们有一个具有相同类型的“已接收”属性的对象。当我们尝试将控件绑定到对象时,会抛出以下 InvalidCastException:
从 'System.DateTime' 到 'System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'的无效转换。
这是我们正在做的事情:
对象属性:
private System.DateTime? _dateTimeReceived;
public System.DateTime? DateTimeReceived
{
get
{
return this._dateTimeReceived;
}
set
{
this._dateTimeReceived = value;
this.OnChanged("DateTimeReceived", value); //Implements INotifyPropertyChanged and fires PropertyChanged event
}
}
控件属性:
private System.DateTime? _value;
[System.ComponentModel.Category("Behavior")]
[System.ComponentModel.Description("The current date value for this control")]
public new System.DateTime? Value
{
get
{
return this._value;
}
set
{
this._value = value;
}
}
在应用程序中,这里是抛出异常的地方:
this.dateReceived.DataBindings.Add("Value", this._object, "DateTimeReceived");
如您所见,对象的属性 (this._object.DateTimeReceived) 是 System.DateTime?类型和控件的属性 (this.dateReceived.Value) 是 System.DateTime?输入。
为什么这会导致InvalidCastException?以及我们如何纠正它以使其正确绑定?
更新 2009-10-29 14:26 CDT:
这是堆栈跟踪:
在 System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider 提供程序)
在 System.DateTime.System.IConvertible.ToType(类型类型,IFormatProvider provider)
在 System.Convert.ChangeType(Object value, Type 转换类型,IFormatProvider 提供程序)
在 System.Windows.Forms.Binding.FormatObject(对象值)
at System.Windows.Forms.Binding.PushData(布尔力)
at System.Windows.Forms.Binding.UpdateIsBinding()
在 System.Windows.Forms.Binding.CheckBinding()
在 System.Windows.Forms.Binding.SetListManager(BindingManagerBase bindingManagerBase)
在 System.Windows.Forms.ListManagerBindingsCollection.AddCore(绑定 数据绑定)
在 System.Windows.Forms.BindingsCollection.Add(绑定绑定)
at System.Windows.Forms.BindingContext.UpdateBinding(BindingContext newBindingContext, 绑定绑定)
at System.Windows.Forms.Binding.SetBindableComponent(IBindableComponent 价值)
在 System.Windows.Forms.ControlBindingsCollection.AddCore(绑定 数据绑定)
在 System.Windows.Forms.BindingsCollection.Add(绑定绑定)
at System.Windows.Forms.ControlBindingsCollection.Add(字符串 propertyName, Object dataSource, String dataMember, Boolean formattingEnabled,DataSourceUpdateMode updateMode,对象 nullValue, String formatString, IFormatProvider formatInfo)
at System.Windows.Forms.ControlBindingsCollection.Add(字符串 属性名、对象数据源、字符串数据成员)
【问题讨论】:
-
您的异常的完整堆栈跟踪是什么(请在 VS 调试设置中禁用“仅我的代码”,以便它显示 .NET Framework 本身的堆栈帧)?
标签: c# winforms data-binding datetime nullable