简体   繁体   中英

How do I extend a Control in WinForms?

Any control. But preferably all of them (TextBox, Panel, Button, LinkLabel, TabControl, etc). What I would like to do is:

public class Something
{
   public String isBetterThan { get; set; }
   public String Author { get; set; }
}

public void button1_Click(object sender, EventArgs e)
{
   panelControl1.ClassObject = new Something()
      {
         isBetterThan = "nothing.",
         Author = "Unknown"
      };
}

So from the code above, you can see that it acts similarly to the .Location property, where you assign it a new value. I would like to store this information, so that later on, I can simply do this:

public void getClassDetailsButton_Click(object sender, EventArgs e)
{
   Something something = (Something)panelControl1.ClassObject;
   MessageBox.Show("Something is better than " + something.isBetterThan);
}

You can create a Custom control by inheriting from the control you are trying to add the function to. Something like this should work ( using a button as an example )

using System;
using System.Collections.Generic;
using System.Linq; 
using System.Text;
using System.Windows.Forms; 

namespace WindowsFormsApplication1
{
    class SomethingButton : Button
    {
        public Something mySomething
        { get; set; }
    }

    public class Something
    {
        public String isBetterThan { get; set; }
        public String Author { get; set; }
    }

}

Usuage

somethingButton1.mySomething = new Something() { isBetterThan = "nothing", 
                                                 Author = "Unknown" 
                                               };

I think the answer you are looking for is the DefaultValue attribute. You set it once in the class and then whenever the object is created it gets assigned the value. There's a couple of pitfalls with saving the object data using this attribute so use caution and do regression testing.

http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute(v=VS.71).aspx

[DefaultValue("Author Name")]

You can always create a class that extends off of the control, and override the methods that you'd like to add functionality to.

public class MyTextBox : TextBox {

public String isBetterThan { get; set;}
public String author {get; set;}

protected override void OnMouseLeave(MouseEventArgs e)        
{            
     base.OnMouseLeave(e);
     // do something
     isBetterThan = this.Text;
}    
}

Then, add the control to your Form. You can treat it like a regular TextBlock, but also ask it for isBetterThan and Author.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM