如何判断控件是否来自MasterPage



当遍历页面上所有控件的集合(来自Page.Controls和这些控件的子控件及其子控件等)时,如何判断控件是否来自页面的母版页?

以下内容似乎有效,但感觉有点脏。有没有更好的方法来获取这些信息?

更新:抱歉,错过了早些时候的一些代码。

List<Control> allControls = GetAllControls(this.Page)
foreach (Control c in allControls)
{
       bool isFromMaster = c.NamingContainer.TemplateControl.GetType().BaseType.BaseType == typeof(MasterPage);
}

其中GetAllControls递归地获取页面上的所有控件

感谢

给定对Control的引用,您可以递归地查看Parent属性:

bool IsFromMasterPage(Control control)
{
    while(control.Parent != null)
    {
        if (control.Parent is MasterPage) return true;
        control = control.Parent;
    }
    return false;
}

Page.Controls仅包含来自当前页面的控件

如果您想检查MasterPage控件,请使用:

this.Master.Controls

另一方面,如果你想在你的页面上找到MasterPage控件:

IEnumerable<MasterPage> masterPageControls = this.Page.Controls.OfType<MasterPage>();

尽管您只能有一个MasterPage关联到您的页面

解决方案通过母版页中的控件,不包括内容占位符的子控件(因为这些控件为您提供了从页面本身添加的控件)。

public static bool IsFromMasterPage(Control control)
{
    if (control.Page.Master != null)
    {
        // Get all controls on the master page, excluding those from ContentPlaceHolders
        List<Control> masterPageControls = FindControlsExcludingPlaceHolderChildren(control.Page.Master);
        bool match = masterPageControls.Contains(control);
        return match;
    }
    return false;
}    
public static List<Control> FindControlsExcludingPlaceHolderChildren(Control parent)
{
    List<Control> controls = new List<Control>();
    foreach (Control control in parent.Controls)
    {
        controls.Add(control);
        if (control.HasControls() && control.GetType() != typeof(ContentPlaceHolder))
        {
            controls.AddRange(FindControlsExcludingPlaceHolderChildren(control));
        }
    }
    return controls;
}

最新更新