winform 用户控件事件在父窗体触发


User control:

 
[Browsable(true)] [Category("Action")] 
[Description("调用用户按钮事件")]
public event EventHandler ButtonClick;
 
protected void Button1_Click(object sender, EventArgs e)
{
    //bubble the event up to the parent
    if (this.ButtonClick!= null)
        this.ButtonClick(this, e);               
}
 
 
 


 
Form:

 
UserControl1.ButtonClick += new EventHandler(UserControl_ButtonClick);
 
protected void UserControl_ButtonClick(object sender, EventArgs e)
{
    //handle the event 
}


推荐一种更简洁的方法:
 
UserControl:

public System.Windows.Forms.Panel panel;
 


 
 
Winform:
 

UserControl item = new UserControl();
item.panelTitle.Click += panel1_Click;
 
protected void panel1_Click(object sender, EventArgs e)
{
   var form = (UserControl)(((Panel)sender).Parent);
   Method(sender, e);
}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
窗体中刷新窗体可以使用委托和事件来实现。具体步骤如下: 1. 在窗体中定义一个委托和事件: ```csharp public delegate void RefreshEventHandler(); public event RefreshEventHandler RefreshEvent; ``` 2. 在窗体中通过构造函数传递窗体对象,并在需要刷新时触发事件: ```csharp public partial class ChildForm : Form { private ParentForm parentForm; public ChildForm(ParentForm parentForm) { InitializeComponent(); this.parentForm = parentForm; } private void button1_Click(object sender, EventArgs e) { // 窗体按钮点击时触发事件 parentForm.RefreshEvent?.Invoke(); } } ``` 3. 在窗体中订阅事件,并在事件处理程序中执行刷新操作: ```csharp public partial class ParentForm : Form { public ParentForm() { InitializeComponent(); // 订阅窗体事件 childForm.RefreshEvent += RefreshData; } private void RefreshData() { // 刷新操作 // ... } } ``` 如果要在窗体中改变窗体控件的值,可以通过将窗体对象传递给窗体,并在窗体中直接修改窗体控件的值。具体步骤如下: 1. 在窗体中定义一个窗体对象,并在构造函数中初始化: ```csharp public partial class ChildForm : Form { private ParentForm parentForm; public ChildForm(ParentForm parentForm) { InitializeComponent(); this.parentForm = parentForm; } private void button1_Click(object sender, EventArgs e) { // 修改窗体控件的值 parentForm.label1.Text = "新的文本内容"; } } ``` 2. 在窗体中打开窗体时将自身对象传递给窗体: ```csharp private void button1_Click(object sender, EventArgs e) { ChildForm childForm = new ChildForm(this); childForm.Show(); } ``` 这样,在窗体中就可以直接修改窗体控件值了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值