如何将新的自定义字段添加到所有窗体控件 [英] How to add new custom field to All of the form controls

查看:81
本文介绍了如何将新的自定义字段添加到所有窗体控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望所有控件都具有新字段,以便可以在for循环中使用它.
我的意思是,我只想向该控件添加一些元数据和通用数据,以便我可以根据该元数据来操作每个控件(不单独).


喜欢这个

I want all my control to have new field so that I can use it in for loop.
I mean that I just want to add some meta and common data to that controls so that I can operate each control depending upon that meta data(without individually).


Like this

MyCustomType mct = new MyCustomType();
...
textBox1.MyCustomField=mct;

button1.MyCustomField=mct;
.
.


//on some event handler

for(int i =0; i<this.controls.count;i++){>
  MyCustomType mct=this.Controls[i].MyCustomField;
  if(mct.Status){
     this.Controls[i].Visible=false;
         ...
   }
}

推荐答案

请查看上一个问题的答案:最终目标.

—SA
Please see the answers to your previous question: How to allow My class to add custom fields and properties by other class on the fly[^].

Let me tell you that you have no idea what you''re trying to do. The field would be untyped and very hard to use. I would like to see how you cope with the task.

Let''s simplify. First step: make all your controls custom. Yes, do not inject anything. Create some interface(s) you may need for loops and have implement it (or them) in all control classes you want to participate in you loops. When you need to do those loops, obtain an interface reference from each control and use it.

Next step: To help with the next step, I want to know what do you want to do in those loops. I bet you don''t need anything special. Please make sure you not just explain it in terms of "I want", but explain your ultimate goals.

—SA


这可能是一个愚蠢的问题,但是您确实意识到,不必为添加信息而进行任何繁琐甚至复杂的事情.运行时(或设计时,尽管运行时更灵活)的任何控件.

所有控件都有Tag 属性,您可以自由使用.它是一个object引用,因此您可以在其中放置任何类型的值,只要在要使用它时就将其回退即可.由于它是控件的一部分,因此每个实例都有一个不同的控件.

那样对您的应用有用吗?

This may be a silly question, but you do realize that you don''t have to do anything drastic, or even complex to add information to any control at run time (or design time, though run time is more flexible).

All controls have a Tag property, which you are free to use. It is an object reference, so you can put any type of value in it, as long as you cast it back when you want to use it. Since it is part of the Control, there is a different one available for each instance.

Won''t that do for your app?

Button b = new Button();
b.Tag = "b";
Controls.Add(b);
TextBox t = new TextBox();
t.Tag = new List<string>() { "Hello", "goodbye" };
Controls.Add(t);
...
foreach (Control c in Controls)
   {
   TextBox t = c as Textbox;
   if (t != null)
      {
      List<string> list = t.Tag as List<string>;
      ...
      }
   }


这篇关于如何将新的自定义字段添加到所有窗体控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆