【问题标题】:Is there any user control or master control in C# or any other way to call reusable codeC# 中是否有任何用户控件或主控件或任何其他调用可重用代码的方式
【发布时间】:2012-06-21 02:53:24
【问题描述】:

我是 C# 编程新手,你可能会觉得它非常简单...... 我正在使用带有添加、更新、删除、取消和关闭按钮的菜单栏(工具条)... 在添加按钮中我有....

private void btn_Add_Click(object sender, EventArgs e)
    {
NewSavebtn();
}

public void NewSavebtn()
        {
           if (btn_Add.Text == "&New")
            {
                btn_Add.Text = "&Save";
                btn_Edit.Enabled = false;
                btn_Delete.Enabled = false;
                txtDetailName.Enabled = true;
                TxtHeadName.Enabled = true;


                   UnLock();
                }



else if (btn_Add.Text == "&Save")
            {

            save_data();
            Lock(); 
            btn_Add.Text = "&Add";
            btn_Edit.Enabled = true;
            btn_Delete.Enabled = true;
            ClearAll();
            txtDetailName.Enabled = false;
         }
        else
            MessageBox.Show("cant save data");
    }


    #region Clear Lock Unlock
    public void ClearAll()
    {

        foreach (Control ctl in this.Controls)
        {
            if (ctl is TextBox || ctl is ComboBox)
            {
                ctl.Text = "";
            }
        }

    }

    public void Lock()
    {

        foreach (Control ctl in this.Controls)
        {
            if (ctl is TextBox || ctl is ComboBox)
            {
                ctl.Enabled=false ;
            }
        }

    }
    public void UnLock()
    {

        foreach (Control ctl in this.Controls)
        {
            if (ctl is TextBox || ctl is ComboBox)
            {
                ctl.Enabled=true ;
            }
        }

    }
    #endregion

我想在近 200 多种表单中添加相同的代码。 谁能告诉我我想为它做些什么。 c#中是否有像asp.net这样的用户控件或主控件,以便可以将常用代码放在一边并在必要时调用... 因为如果我将 NewSavebtn() 和其他方法放在不同的类中说 class1 并尝试从 form1 调用它...

class1 c1 =new class1(this);
c1.NewSavebtn(this);

它不起作用.... 提前谢谢....

【问题讨论】:

  • NewSavebtn 是属性还是控件还是方法?

标签: c#


【解决方案1】:

如果这是针对 Windows 窗体应用程序的,那么您可以 Create a User Control,如果您正在开发 WPF 应用程序,那么您可能会看到以下教程:How to Create a WPF User Control & Use It in a WPF Application ( C# )

【讨论】:

    【解决方案2】:

    您可以在 windows 窗体中创建用户控件以通过一百个窗体使用。但是,我认为您的代码在维护方面不容易更改。您应该使用委托来处理事件。为了将来的改进,您可以使用委托Execute a delegate in the ui thread (using message pump) 轻松定义结果。

    【讨论】:

      猜你喜欢
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-20
      相关资源
      最近更新 更多