繁体   English   中英

通过“内容”页面上的自定义控件设置MasterPage属性

[英]Setting MasterPage property from a custom control on a Content page

我知道之前已经在其他主题中讨论过这个主题,但是我的问题是关于样式和OOP原理,而不是方法。 在这种情况下,我们有一个MasterPage,一个Content页面和一个在Content页面中使用的自定义控件。 MasterPage在MyNamespace命名空间中,并公开一个属性MasterTitle,我们需要从自定义控件(MyControl)设置此属性。 我们还添加了<%@ MasterType VirtualPath =“〜/ Site.Master”%>,以便我们可以从内容页面引用母版页。 一位程序员使用了以下代码行来设置MasterTitle属性:

   ((MyNamespace.Site)Page.Master).MasterTitle = "Some Title";

另一个程序员做了很多复杂的事情。 在定制控件中,他声明了一个委托:

   public delegate void SetMasterTitleDelegate(string masterTitle);

   public SetMasterTitleDelegate SetMasterTitle;

然后在内容页面的Page_Init()中:

  MyControl.SetMasterTitle = (masterTitle) => { Master.MasterTitle = masterTitle; };

在MyControl的Page_Load()事件中,设置了MasterTitle属性:

  SetMasterTitle("Some Title");

我想知道完成此任务的每种方法的优缺点,因为它们与OOP原则有关。

谢谢。

有很多方法可以完成此任务。 您可以在每个内容页面上创建一个“标题”属性,并在该属性的设置器中设置母版页的标题。 另一种方法是在每个内容页面上实现一个界面,该界面可用作母版页的“合同”。 您可以在设置母版页标题并从内容页进行设置的基础上使用。

但是我个人会选择(和使用)您的第一种方法。 干净且易于遵循。

但是从OOP角度来看,我认为MS建议使用站点地图来设置标题和构建菜单/面包屑。

让我们先谈谈方法:

方法1:第一种方法非常简单明了,最简单。 无需太多开销即可使用它。 结论-好的方法

方法2:第二种方法似乎要复杂得多,我个人会避免使用它。 在更大的上下文中,您开发的每个自定义控件或子页面都需要此类方法。

我可以想到的唯一其他方法是,在母版页上使用通常希望在母版页中引用的属性和方法来创建和实现接口。 所以

public interface IMasterContract {
    public string Title {get; set;}
}

然后,您可以创建一个继承自System.Web.UI.Page的基类,并在该基类中实现相同的接口。 在这里,您可以决定是否要将要设置的标题设置为母版(如果存在),或者是否要进行其他操作。 所以,

public abstract class AppPage : System.Web.UI.Page, IMasterContract
{
    public string IMasterContract.Title {
        get
        {
            if(this.Master!=null && this.Master is IMasterContract)
            {
                return ((IMasterContract)this.Master).Title;
            }
            else
            {
                //return the title from whatever control or variable you've stored it in
            }
        }
        set
        {
            if(this.Master!=null && this.Master is IMasterContract)
            {
                ((IMasterContract)this.Master).Title = value;
            }
            else
            {
                //set the title to whatever control or variable you want to stored it in
            }
        }
    }
}

我说过的方法通常对于可维护性是一个巨大变量的大型应用程序很有用。 可以集中进行更改,以反映整个应用程序。

对于较小的应用程序,或者如果您尝试尝试的功能仅限于几个位置,则我不会做我所显示的范围,而是选择方法1。

暂无
暂无

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

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