来自其事件处理程序的访问控制 [英] Access control from its event handler

查看:26
本文介绍了来自其事件处理程序的访问控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不提及其名称的情况下访问其事件处理程序中的控件参数.

I want to access a control's parameters inside it's event handler without mentioning its name.

一个例子很清楚:

private void label1_Click(object sender, EventArgs e)
{
    self.text="clicked";//pseudo code
}

我想要这样的东西,它将 label1 的文本更改为点击"或我想要的任何内容.

I want somthing like this which would change the text of label1 to "clicked" or whatever I want.

我想这样做是因为我正在制作的软件由大量标签和文本框组成我更喜欢在每个事件处理程序中复制和粘贴单个代码,而不是为每个控件分别键入一个.

I want to do this because the software I'm making consists of large number of labels and textboxes and I prefer to just copy and paste the single code in each event handler rather than typing seperate one for each control.

可以在 C# 中完成这样的事情吗?我正在使用 winform.

Can something like this be done in C#? I am using winforms.

推荐答案

sender 参数(在 Windows 窗体中的几乎所有事件中)实际上是对触发事件的控件的引用.

The sender parameter (in pretty much all events in Windows Forms) is actually a reference to the control which fired the event.

换句话说,您可以简单地将其转换为 Control(或 Label 或其他):

In other words, you can simply cast it to a Control (or Label, or whatever):

private void label1_Click(object sender, EventArgs e)
{
      var ctrl = sender as Control; // or (Control)sender
      ctrl.Text = "clicked";
}

这允许您将相同的处理程序方法附加到多个控件上的事件,并使用 sender 参数区分它们:

This allows you to attach the same handler method to events on multiple controls, and differentiate them using the sender parameter:

// the `label_Click` method gets called when you click on each of these controls
label1.Click += label_Click;
label2.Click += label_Click;
label3.Click += label_Click;

如果您想完全避免强制转换,另一种方法是使用 lambda 来捕获父控件:

Another way to do this, if you want to avoid casting altogether, might be to use a lambda to capture the parent control:

label1.Click += (sender, args) => label1.Text = "Clicked";

这篇关于来自其事件处理程序的访问控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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