.net 如何更新绑定到WindowsForms.TextBox.DataSource。。嗯。。每个TextChanged事件的数据源(键入期间)?

.net 如何更新绑定到WindowsForms.TextBox.DataSource。。嗯。。每个TextChanged事件的数据源(键入期间)?,.net,winforms,data-binding,textbox,.net,Winforms,Data Binding,Textbox,如何更新绑定到WindowsForms.TextBox.DataSource。。嗯。。每个TextChanged事件的数据源(键入期间) 如果您想在键入时更新某些“计数器”或“错误状态”,这将非常有用 以前我有时使用过这段代码,但它看起来太复杂了。可能还有其他更简单的解决方案吗 class FlashTextBox:TextBox { protected override void OnTextChanged(EventArgs e) { Binding binding = thi

如何更新绑定到WindowsForms.TextBox.DataSource。。嗯。。每个TextChanged事件的数据源(键入期间)

如果您想在键入时更新某些“计数器”或“错误状态”,这将非常有用

以前我有时使用过这段代码,但它看起来太复杂了。可能还有其他更简单的解决方案吗

class FlashTextBox:TextBox
{
  protected override void OnTextChanged(EventArgs e)
  {
   Binding binding = this.DataBindings["Text"];
   if (binding!=null)
   {
    PropertyManager propertyManager = 
                                binding.BindingManagerBase as PropertyManager;
    if (propertyManager!=null)
    {
               PropertyInfo pinfo =      
                                    binding.DataSource.GetType()
                                    .GetProperty(binding.BindingMemberInfo.BindingField,
                                    BindingFlags.Instance | BindingFlags.Public);
     pinfo.SetValue(binding.DataSource, this.Text, null);
    } 
   }
                    if (isAutoScrollVisible)
                    {
                            ChangeScrollVisibility();
                    }
   base.OnTextChanged (e);
  }

  const int WM_KEYDOWN = 0x0100;
  public override bool PreProcessMessage(ref System.Windows.Forms.Message msg)
  {
   if(msg.Msg == WM_KEYDOWN)
   {
    switch((Int32)msg.WParam)
    {
     case (int)Keys.Enter :
      if (EnterPressed!=null)
       EnterPressed(this,EventArgs.Empty);
      break;
    }
   } 
   return base.PreProcessMessage(ref msg);
  }
}

下面的代码片段显示了如何将TextBox.Text属性绑定到业务对象的PropertyName属性。确保将DataSourceUpdateMode.OnPropertyChanged设置设置为DataSourceUpdateMode.OnValidation是TextBox控件的默认设置

var bindingSource = new System.Windows.Forms.BindingSource();
bindingSource.DataSource = businessObject;
flashTextBox.DataBindings.Add(new System.Windows.Forms.Binding(
    "Text", 
    bindingSource, 
    "PropertyName", 
    true, 
    System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged
    ));
有关更多详细信息,请参阅MSDN文档: