代码之家  ›  专栏  ›  技术社区  ›  Roman Pokrovskij Archil Labadze

如何更新绑定到windowsforms.textbox.datasource的。嗯…每个textChanged事件的数据源(键入期间)?

  •  1
  • Roman Pokrovskij Archil Labadze  · 技术社区  · 15 年前

    如何更新绑定到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);
      }
    }
    
    1 回复  |  直到 13 年前
        1
  •  3
  •   Ryan Lundy    13 年前

    下面的代码段显示如何将textbox.text属性绑定到业务对象的propertyname属性。确保将DataSourceUpdateMode.OnPropertyChanged设置设置为DataSourceUpdateMode.OnValidation是文本框控件的默认设置。

    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文档: http://msdn.microsoft.com/en-us/library/system.windows.forms.binding.aspx

    推荐文章