在表单上为按钮分配和更改事件的推荐方法是什么?

时间:2012-07-03 08:38:01

标签: c# winforms

我有一个表格,我想在各种情况下'可重复使用'。主要是显示和打印信息。表单有2个按钮和一个列表框

我希望能够将一个对象传递给表单,该表单告诉表单按下按钮时要执行的操作(例如显示MessageBox,打印列表框的内容或关闭表单)

我正在使用if语句来确定要分配给我的按钮的事件...有更好的方法吗?

理想情况下,我想从初始调用代码中设置事件,而不是使用名为“Action”的枚举

     ==========calling code=================
                var information = new Information();                
                information.Action = Action.Print;
                var frmInformation = new frmInformation(information);
                frmInformation.Show(this);

    ====================information class======================
    public class Information
        {
            public delegate void OkButtonDelegate();        
            public IList<string> information{ get; set; }

            public Information()
            {
                information = new BindingList<string>();
            }

    ===============information form======================
     public partial class frmInformation : Form
        {
            private readonly Information _information;
            public Information.OkButtonDelegate _delegate;   

            public frmInformation(Information information)
            {
                _information = information;
                InitializeComponent();
                SetupForm();
            }


            private void SetupForm()
            {                         
                if (_information.Action== Action.Print)
                    _delegate = new Information.OkButtonDelegate(Print);
                else if (_information.Action == Action.Close)
                    _delegate = new Information.OkButtonDelegate(Close);
              }

        private void ShowMessageBox()
                {
                    MessageBox.Show("lalalalalala");
                }


                public static void Print()
                {
                    //take the contente out of listbox and send it to the printer
                }

 private void btnSend_Click(object sender, EventArgs e)
        {
            _delegate();

        }

1 个答案:

答案 0 :(得分:0)

你可以这样改变

switch (_information.Action) {
   case Action.Print:
      btnSend.Click += (s,e) => Print();
      break;
   case Action.Close:
      btnSend.Click += (s,e) => Close();
      break;
}

您不需要委托类型,生成Click处理程序和_delegate变量。