0

我有以下要在不同的自定义控件中调用的类。这些控件自定义具有winforms 的外观。控件的每个类型都是 Control1、control2...我可以有一个 Type 的通用构造函数,其中 T 可以是 Namespace.C1、Namespace.C2、Namespace.C3、Namespace.C4...、Namespace.C8

问题:SimpleDirtyTracker _tracker = new SimpleDirtyTracker(Type) 其中 T 是一个有很多文本框的用户控件,而不是 SimpleDirtyTracker _tracker = new SimpleDirtyTracker(Form frm),

  public class SimpleDirtyTracker
    {
      private Form _frmTracked;  
      private bool _isDirty;

      // property denoting whether the tracked form is clean or dirty
      public bool IsDirty
      {
          get { return _isDirty; }
          set { _isDirty = value; }
      }

      // methods to make dirty or clean
      public void SetAsDirty()
      {
          _isDirty = true;
      }

      public void SetAsClean()
      {
          _isDirty = false;
      }


//Needs a generic type in the constructor. Not a form, mostly a user control of type Namespace.Control1 or Namespace.Control2
      public SimpleDirtyTracker(SomeType T) where T is a custom control
      {
          _frmTracked = frm;
          AssignHandlersForControlCollection(frm.Controls);
      }


      // recursive routine to inspect each control and assign handlers accordingly
      private void AssignHandlersForControlCollection(Control.ControlCollection coll)
      {
          foreach (Control c in coll)
          {
              if (c is TextBox)
                  (c as TextBox).TextChanged += new EventHandler(SimpleDirtyTracker_TextChanged);

              if (c is CheckBox)
                  (c as CheckBox).CheckedChanged += new EventHandler(SimpleDirtyTracker_CheckedChanged);

              // ... apply for other input types similarly ...

              // recurively apply to inner collections
              if (c.HasChildren)
                  AssignHandlersForControlCollection(c.Controls);
          }
      }

      // event handlers
      private void SimpleDirtyTracker_TextChanged(object sender, EventArgs e)
      {
          _isDirty = true;
      }

      private void SimpleDirtyTracker_CheckedChanged(object sender, EventArgs e)
      {
          _isDirty = true;
      }

    }
}

此类将从自定义控件中调用。这些主要是带有用作 Winforms 的文本框的控件

     private void Control_Load(object sender, EventArgs e)
            {
                // in the Load event initialize our tracking object
//To Pass a generic type.   //Needs a generic type in the constructor. Type T could be Namespace.C1...Namespace.C8

                _dirtyTracker = new SimpleDirtyTracker(Custom Control T);
                _dirtyTracker.SetAsClean();
            }
4

0 回答 0