0

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

我希望能够将一个对象传递给表单,告诉表单按下按钮时要做什么(例如显示一个消息框,打印出列表框的内容或关闭表单)

我正在使用 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();

        }
4

1 回答 1

0

你可以这样改

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

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

于 2012-07-03T09:04:27.813 回答