来自WinForms.NET 中的数据绑定和 Nullable 类型
设想
- 您有一个具有 Nullable 属性的实体类型。
- 您有一个绑定到该属性的 TextBox。
- 当用户清除 TextBox 中的文本时,您希望将属性的值设置为 null。
问题
清除绑定到 Nullable 类型的 TextBox 时,数据绑定的结果根本不会成功。
解决方案
在本文中,我将展示如何使用 Extender Provider 来做到这一点。
只需将 Component 类添加到您的项目中,该类也实现了 IExtenderProvider 接口
[ProvideProperty("NullableBinding", typeof(TextBox))]
public partial class NullableExtender : Component, IExtenderProvider
ProviderProperty 属性表明,在将 NullableExtender 组件添加到您的 Form 或 UserControl 时,所有的 TextBox 都将具有一个名为 NullableBinding 的附加属性。在 VS.NET 设计器中它看起来像这样:

现在为这个属性实现一些功能:
private Dictionary<Control, Boolean> _nullables = new Dictionary<Control,bool>();
/// <summary>
/// This is the get part of the extender property.
/// It is actually a method because it takes the control.
/// </summary>
/// <param name="control"></param>
[DefaultValue(false),
Category("Data")]
public bool GetNullableBinding(Control control)
{
bool nullableBinding = false;
_nullables.TryGetValue(control, out nullableBinding);
return nullableBinding;
}
/// <summary>
/// This is the set part of the extender property.
/// It is actually a method because it takes the control.
/// </summary>
/// <param name="control"></param>
/// <param name="nullable"></param>
public void SetNullableBinding(Control control, bool nullable)
{
if (_nullables.ContainsKey(control))
_nullables[control] = nullable;
else
_nullables.Add(control, nullable);
if (nullable)
{
// Add a parse event handler.
control.DataBindings["Text"].Parse += new ConvertEventHandler(NullableExtender_Parse);
}
}
/// <summary>
/// When parsing, set the value to null if the value is empty.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void NullableExtender_Parse(object sender, ConvertEventArgs e)
{
if (e.Value.ToString().Length == 0)
{
e.Value = null;
}
}
实际完成上述技巧的代码是为数据绑定 Parse 事件添加事件处理程序。如果值为空字符串,则事件处理程序只需将值设置为 null,并且数据绑定成功。
该属性的默认值设置为 false,因为大多数属性不是 Nullable 类型,我建议不要将这些属性的 NullableBinding 设置为 true ... ;)