简体   繁体   English

在将方法和事件处理程序从背后的用户控件迁移到类库时需要帮助。 或需要知​​道是否可能

[英]Need help in migrating methods and event handlers from a usercontrols code-behind to a class library. Or need to know if its possible

I have come up with a way of making my code more re-usable but am wondering if there is a better way. 我想出一种使我的代码更可重用的方法,但是我想知道是否有更好的方法。 My approach requires copying and pasting the same code into the code-behind of each usercontrol. 我的方法要求将相同的代码复制并粘贴到每个用户控件的代码背后。 All I did is minimize the amount of changes I need to make after each copy and past. 我所做的就是最大程度地减少每次复制和过去之后需要进行的更改数量。

Question

Is there a way I can write the code so it can be re-used without having to copy and paste? 有没有一种方法可以编写代码,以便无需复制和粘贴即可重新使用它? Like putting the methods & event handlers into a class library and having each usercontrol reference it and call it from there. 就像将方法和事件处理程序放入类库并让每个用户控件引用它并从那里调用它一样。

Below is a more detailed description of what I am currently doing as well as the source for one of the usercontrols. 下面是我目前正在做的事情以及其中一个用户控件的更详细的描述。

I have 20 usercontrols that are all identical except they use different classes/entities. 我有20个完全相同的用户控件,除了它们使用不同的类/实体。 For instance one of the entites is StudentInjury and another is PoliceReport. 例如,一个实体是StudentInjury,另一个是PoliceReport。 Basically each usercontrol displays a collection of the entities in a grid and contain add,edit,delete & undelete buttons. 基本上,每个用户控件都会在网格中显示实体的集合,并包含添加,编辑,删除和取消删除按钮。 Each entity has different properties that display in the grid so I am not attempting to re-use the aspx portion of the usercontrol. 每个实体都有在网格中显示的不同属性,因此我不打算重复使用usercontrol的aspx部分。

Based on my limited knowledge I made the code-behind as easy to re-use as possible. 基于我的有限知识,我使隐藏代码尽可能易于重用。 I did this by adding comments in the code such as: 我通过在代码中添加注释来做到这一点,例如:

// 1. Set the entityCollection
var entityCollection = incident.StudentInjuries;

and

// 2. Set entityCollectionWithDeletes
StudentInjuryCollection entityCollectionWithDeletes = StudentInjuryCollection.LoadByIncidentWithDeletes(incident);

So when creating the code-behind for the PoliceReport usercontrol I can simple copy all of the StudentInjury code-behind into the PoliceReport usercontrol code-behind and after making the replacments it would look like below. 因此,当为PoliceReport用户控件创建后台代码时,我可以将所有StudentInjury代码后台代码简单地复制到PoliceReport用户控件代码后台,并在进行替换后如下所示。

// 1. Set the entityCollection
var entityCollection = incident.PoliceReports;

and

// 2. Set entityCollectionWithDeletes
PoliceReportCollection entityCollectionWithDeletes = PoliceReportCollection.LoadByIncidentWithDeletes(incident);

Below is the code for one of the usercontrols: 下面是其中一个用户控件的代码:

public partial class StudentInjuryControl : System.Web.UI.UserControl
{
    // 1. Set the name of the entity
    public const string EntityName = "StudentInjury";

    public void Refresh(Incident incident, FormMode mode, bool showDeletedItems)
    {
        // 1. Set the entityCollection
        var entityCollection = incident.StudentInjuries;

        if (entityCollection.Count > 0)
        {
            YesNoRadioButtonList.SelectedValue = "Yes";
            YesNoRadioButtonList.Enabled = false;
        }
        else
        {
            YesNoRadioButtonList.Enabled = true;
            if (YesNoRadioButtonList.SelectedValue == "Yes")
            {   // Needed in case cancel button clicked
                YesNoRadioButtonList.ClearSelection();
            }
            if (mode != FormMode.Add)
            {
                YesNoRadioButtonList.SelectedValue = "No";
            }
        }

        int numberOfRecords;
        if (showDeletedItems)
        {
            // 2. Set entityCollectionWithDeletes
            StudentInjuryCollection entityCollectionWithDeletes = StudentInjuryCollection.LoadByIncidentWithDeletes(incident);
            numberOfRecords = entityCollectionWithDeletes.Count;
            EntityGridView.DataSource = entityCollectionWithDeletes;
        }
        else
        {
            numberOfRecords = entityCollection.Count;
            EntityGridView.DataSource = entityCollection;
        }
        EntityGridView.DataBind();

        if (numberOfRecords > 0)
        {
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "show" + EntityName + "Container", "document.getElementById('" + EntityName + "Container').style.display='block';", true);
        }
        else
        {
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "hide" + EntityName + "Container", "document.getElementById('" + EntityName + "Container').style.display='none';", true);
        }
    }

    protected void EntityGridView_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Undelete")
        {
            Guid id = new Guid(e.CommandArgument.ToString());
            // 1. Call the undelete method
            StudentInjury.Undelete(id);
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "refresh" + EntityName, "RefreshForm('" + EntityName + "')", true);
        }
    }

    protected void EntityGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // 1. Set the entity
            StudentInjury entity = (StudentInjury)e.Row.DataItem;
            Guid entityId = entity.Id;

            Button deleteButton = (Button)e.Row.FindControl("DeleteButton");
            Button undeleteButton = (Button)e.Row.FindControl("UndeleteButton");
            Button editButton = (Button)e.Row.FindControl("EditButton");

            if (entity.DeleteDateTime.HasValue)
            {
                e.Row.ForeColor = System.Drawing.Color.Red;
                e.Row.Font.Strikeout = true;

                if (undeleteButton != null)
                {
                    undeleteButton.Enabled = true;
                }

                if (editButton != null)
                {
                    editButton.Enabled = false;
                }

                if (deleteButton != null)
                {
                    deleteButton.Enabled = false;
                }
            }
            else
            {
                if (deleteButton != null)
                {
                    deleteButton.Enabled = true;
                    deleteButton.OnClientClick = "return ShowDeleteForm('" + entityId.ToString() + "','" + EntityName + "');";
                }

                if (undeleteButton != null)
                {
                    undeleteButton.Enabled = false;
                }

                if (editButton != null)
                {
                    editButton.Enabled = true;
                    editButton.OnClientClick = "return ShowEditForm('" + entityId.ToString() + "', '" + EntityName + "');";
                }
            }
        }
    }
}

An idea to make the code reusable off the top of my head is to add another layer between all your controls that has common functionality that all controls can use. 使代码可重复使用的想法是在所有控件之间添加另一层,该层具有所有控件可以使用的通用功能。

For example make a base control class that inherits System.Web.UI.UserControl as follows: 例如,制作一个继承System.Web.UI.UserControl的基本控件类,如下所示:

public class BaseControl : System.Web.UI.UserControl
{
   //common control logic goes here 
}

Then your concrete control would look like this: 然后,您的具体控件将如下所示:

public partial class StudentInjuryControl : BaseControl
{
}   

Then you just need to make sure to make your common methods more generic so that they will work for other controls. 然后,您只需要确保使通用方法更通用即可将它们用于其他控件。

暂无
暂无

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

相关问题 需要帮助从我的代码后面格式化html - Need help formatting html from my code-behind 需要从后面的代码中调用Javascript方法 - Need to call a Javascript method from the code-behind WPF初学者:如何绑定到类的实例并在代码隐藏事件处理程序中引用它 - WPF beginner: How to bind to an instance of a class and reference it in code-behind event handlers 如何引用不在代码隐藏中但在另一个 object 中的事件处理程序? - How to reference event handlers that are not in code-behind, but are in another object? 如何使UserControls的代码隐藏继承基类? - How can I make the code-behind of UserControls inherit a base class? Maui Collection View:需要在代码隐藏中访问同级控件 - Maui Collection View: Need to access sibling controls in code-behind 我是否需要在代码隐藏中调用NotifyPropertyChange()? - Do I need to call NotifyPropertyChange() in code-behind? ASP.Net-需要单击代码后面的按钮,这样我才能弹出错误消息 - ASP.Net - need to click a button from the code-behind so I can pop an error message 如何从代码隐藏中访问用于填充XAML类的DataContext的属性/方法? - How can I access properties/methods of the DataContext used to populate a XAML class from the code-behind? 从代码隐藏(C#、WPF)添加时,用户控件无法在 ListBox 中正确显示 - UserControls aren't displayed properly in ListBox when added from Code-behind (C#, WPF)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM