控件具有Generic构造函数Type <t> </t>

时间:2013-10-28 17:32:46

标签: c# winforms

我有以下类,它将在不同的自定义控件中进行调用。这些控件自定义具有winforms的外观。每个控件都是Control1,control2的类型......我可以在T中使用Type的泛型构造函数 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();
            }

0 个答案:

没有答案