简体   繁体   English

在 c# 中添加 winform 用户控制事件

[英]adding winform user control event in c#

I am learning c# at the moment.我现在正在学习 c#。

I have setup a winform user control (called aUC) with 1 button (called simpleButton1) in vb I can do the following.我在 vb 中设置了一个带有 1 个按钮(称为 simpleButton1)的 winform 用户控件(称为 aUC),我可以执行以下操作。

dim aUC1 as aUC = new aUC()

'load user control to form
Me.controls.clear()
Me.controls.Add(aUC1)

' attach button event
AddHandler aUC1.simpleButton1.Click, AddressOf aUCButton_Click

so I try to do the same on c#所以我尝试在 c# 上做同样的事情

aUC aUC1 = new aUC();

' load user control to form
this.Controls.Clear();
this.Controls.Add(aUC1);

aUC1.simpleButton1.Click += aUCBtn_Click;

when I compile I get当我编译我得到

aUC.simpleButton1 is inaccessible due to its protection level.

I notice when I look at the designer code on user control当我查看用户控件上的设计器代码时,我注意到

in vb it says在VB它说

Friend WithEvents SimpleButton1 As DevExpress.XtraEditors.SimpleButton

in c# it says在 c# 它说

private DevExpress.XtraEditors.SimpleButton simpleButton1;

when I change from private to public on user control design generated code it works ok.当我在用户控件设计生成的代码上从私有更改为公共时,它可以正常工作。

I just wondering if this standard practice in c# to hook user control event on main form is to change the control from private to public;我只是想知道 c# 中在主窗体上挂钩用户控件事件的标准做法是否是将控件从私有更改为公共; or there is a better way/best practice for c#, I prefer not to changing the code on the design generated code in case I accidentally stuff it up.或者对于 c# 有更好的方法/最佳实践,我不想更改设计生成代码上的代码,以防我不小心把它填满。

Thank you.谢谢你。

Regards问候

  • Haris -哈里斯——

As soon as You want to access a button from another class you should change the access modifier to public from the designer there is no other way一旦您想从另一个 class 访问按钮,您应该将访问修饰符从设计器更改为 public 没有其他方法

but I will advise you to learn WPF instead of Winforms但我会建议你学习 WPF 而不是 Winforms

As suggested by Caius,正如凯厄斯所建议的那样,

I create a button click call back on the user control and expose it public event我在用户控件上创建了一个按钮单击回调并将其公开事件

public partial class aUC : UserControl
{
    public EventHandler aUCBtn_Click;

    public aUC()
    {
        InitializeComponent();
    }

    private void simpleButton1_Click(object sender, EventArgs e)
    {
        if (aUCBtn_Click != null)
            aUCBtn_Click(sender, e); // send event to public event
    }
}

and on the main form consume that public event并在主要形式上消费该公共事件

public Form1()
{
    InitializeComponent();

    aUC aUC1 = new aUC();
    this.Controls.Clear();
    this.Controls.Add(aUC1);

    aUC1.aUCBtn_Click += aUC1_Click; // hook to user control event                       
}

private void aUC1_Click(object sender, EventArgs e)
{
    MessageBox.Show("btn click");
}

Thank you.谢谢你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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