读书人

Winform自定义控件怎么执行主页面的方

发布时间: 2012-07-31 12:33:46 作者: rapoo

Winform自定义控件如何执行主页面的方法
例:一个页面上面有一个文本框:textBox1,. 一个全局变量:int i,
一个方法:

C# code
private void showI(){ textBox1.Text=i.ToString();}


页面上拖进来一个用户控件: userControl1.
用户控件上有两个按钮,
一个执行的方法是把主页面的全局变量i加1,
一个执行的方法是把主页面的全局变量i减1,
并且它们要执行当前主页面的方法 showI();当然,这个方法不是固定的.,
 因为如果这个用户控件拖在其它页面上.,其它页面上的方法名可能是 showJ()什么的.

不知道以上要如何实现,研究了一下委托,但是不知道怎么和用户控件使用委托.
 还请哪位高手帮我写个实例. 可以发送 Oicq:834496671 或 mail: 834496671@qq.com




[解决办法]
Form1 f1=userControl1.Parent as Form1;
if(f1!=null)
f1.showI();
[解决办法]
C# code
   public partial class Form1 : Form    {        private UserControl1 uc1 = null;        private int i = 0;        public Form1()        {            InitializeComponent();            //初始化用户控件            uc1 = new UserControl1();            //监听按钮单击引发的事件            uc1.AddEvent += new AddEventHandler(uc1_AddEvent);            uc1.MinusEvent += new MinusEventHandler(uc1_MinusEvent);        }        private void ShowI()        {            textBox1.Text = i.ToString();        }        void uc1_MinusEvent()        {            i--;            ShowI();        }        void uc1_AddEvent()        {            i++;            ShowI();        }        private void Form1_Load(object sender, EventArgs e)        {            groupBox1.Controls.Add(uc1);        }    }//以下是UC    //声明加1和减1委托    public delegate void AddEventHandler();    public delegate void MinusEventHandler();    public partial class UserControl1 : UserControl    {        //声明加1和减1事件,即对应委托的实例        public event AddEventHandler AddEvent = null;        public event MinusEventHandler MinusEvent = null;        public UserControl1()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {            if (AddEvent != null)            {                AddEvent();//触发加1事件            }        }        private void button2_Click(object sender, EventArgs e)        {            if (MinusEvent != null)            {                MinusEvent();//触发减1事件            }        }    }
[解决办法]
2 楼说的可以
[解决办法]
可不可以将i设为静态的,
public static int i;
public static bool str;
然后在页面放个timer,在click里写:
if(str == true)
{
str == false;
showI();
}
而在用户控件里只需:str = true;
[解决办法]
设置自定义控件属性,赋值给属性
通过委托调用主页面方法,操作属性值
参考

读书人网 >C#

热点推荐