【问题标题】:When TextBox TextChanged event is fired?何时触发 TextBox TextChanged 事件?
【发布时间】:2009-10-19 04:16:46
【问题描述】:

我的问题是:

众所周知,ViewState 不负责存储和恢复 TextBox、CheckBox 等控件的值。这是通过 LoadPostData() 方法对实现 IPostBackDataHandler 接口的控件完成的。

而且我们还知道,在 Load 阶段之后,RaisePostBackEvent 阶段会发生并引发相应的事件,例如 Button Click 或如果 TextBox 中的 Text 发生更改,则会触发其 TextChanged 事件。

那么如果 ViewState 不负责,那么系统如何跟踪文本更改以及哪个机制实际触发 TextBox TextChanged 事件?

此时我真的很困惑。

提前致谢。

【问题讨论】:

  • 难道是 ControlState 跟踪并保存了控件的基本信息,但如果是 Control State 那为什么 IPostBackDataHandler 是由 TextBox 实现的?

标签: c# asp.net events


【解决方案1】:

我认为它是这样工作的:

TextBox 控件实现 IPostBackDataHandler 而不是 IPostBackEventHandler,因为它是由其文本状态触发的。所以如果postedValue发生了任何变化,这是确定的

if (presentValue == null || !presentValue.Equals(postedValue)) {
            Text = postedValue;
            return true;
         } 

portion 然后它返回 true 并继续执行,所以最终 TextChanged 被触发。 Pff 令人困惑,但看起来很容易。

using System;
using System.Web;
using System.Web.UI;
using System.Collections;
using System.Collections.Specialized;


namespace CustomWebFormsControls {

   [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")] 
   public class MyTextBox: Control, IPostBackDataHandler {


  public String Text {
     get {
        return (String) ViewState["Text"];
     }

     set {
        ViewState["Text"] = value;
     }
  }      


  public event EventHandler TextChanged;


  public virtual bool LoadPostData(string postDataKey, 
     NameValueCollection postCollection) {

     String presentValue = Text;
     String postedValue = postCollection[postDataKey];

     if (presentValue == null || !presentValue.Equals(postedValue)) {
        Text = postedValue;
        return true;
     }

     return false;
  }


  public virtual void RaisePostDataChangedEvent() {
     OnTextChanged(EventArgs.Empty);
  }


  protected virtual void OnTextChanged(EventArgs e) {
     if (TextChanged != null)
        TextChanged(this,e);
  }


  protected override void Render(HtmlTextWriter output) {
     output.Write("<INPUT type= text name = "+this.UniqueID
        + " value = " + this.Text + " >");
  }
   }   
}

【讨论】:

  • 所以每当一个回发数据改变时,它也会改变控制状态。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-06
  • 1970-01-01
  • 1970-01-01
  • 2015-03-07
  • 2020-01-12
  • 1970-01-01
相关资源
最近更新 更多