简体   繁体   English

自定义控件,公开Button Control的OnClick事件

[英]Custom Control that exposes Button Control's OnClick event

I need to design a custom control that is basically going to be a fancy button, let's call it CtrlButton . 我需要设计一个基本上是一个花哨的按钮的CtrlButton ,我们称之为CtrlButton

I want to drop these on my blank form, then go to the Events for my control and specify what to do for the Click event. 我想将这些放在我的空白表单上,然后转到我控制的事件并指定要为Click事件做什么。

If my custom control CtrlButton contained 1 Windows Form Button named button1 , could I simply expose the underlying Click event handler for the button1 ? 如果我的自定义控件CtrlButton包含在名为1个的Windows窗体Button button1 ,可我只是暴露了潜在的Click事件处理程序button1

public EventHandler Click {
  get { return button1.Click; }
  set { button1.Click = value; }
}

This code doesn't work! 这段代码不起作用! But, that's essentially what I'm trying to do. 但是,这基本上就是我想要做的。

EDIT: I see I was awarded Popular Question for this post, yet it still sits there at -1. 编辑:我看到我被授予这篇文章的热门问题,但它仍然坐在那里-1。 If this question helps you find your answer, please vote it up. 如果这个问题可以帮助您找到答案,请将其投票。

Button.Click is an event, not a property. Button.Click是一个事件,而不是一个属性。 You can't get and set its value, because it's not a property; 你不能得到并设定它的价值,因为它不是一个财产; you can only add and remove handlers, because it's an event and that's how events work. 你只能添加和删除处理程序,因为它是一个事件,事件的工作方式。

But you can write your own event with custom add and remove handlers that wrap the Button: 但您可以使用自定义addremove处理Button的处理程序编写自己的事件:

public event EventHandler Click {
    add { button1.Click += value; }
    remove { button1.Click -= value; }
}

If this is derived from a standard Button control, as this is: 如果这是从标准Button控件派生的,那么:

using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsControlLibrary1
{
   public class RedButton : Button
   {
       public RedButton()
       {
           base.BackColor = Color.Red;
       }
   }
}

the events are available. 这些活动是可用的。 If you have completely customized to make your own button, you will have to wire up all of the events, ala this post . 如果您已经完全自定义制作自己的按钮,那么您将不得不连接所有活动, 这篇文章

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

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