开发者

How to get the List of ContentPlaceHolders of a MasterPage on code-behind?

开发者 https://www.devze.com 2023-01-14 22:08 出处:网络
I need to get the list of ContentPlaceHolders of a MasterPage, but the property protected i开发者_Go百科nternal IList ContentPlaceHolders { get; }

I need to get the list of ContentPlaceHolders of a MasterPage, but the property

protected i开发者_Go百科nternal IList ContentPlaceHolders { get; }

is protected internal, so we can't access them.

Is there any way we could pull them up from the MasterPage (including Reflection)? Thanks.


When you don't mind using reflection and don't mind the risk of your application breaking when migrating to a newer version of .NET, this will work:

IList placeholderNames =
    typeof(MasterPage).GetProperty("ContentPlaceHolders", 
        BindingFlags.Instance | BindingFlags.NonPublic)
    .GetValue(myMasterPage, null) as IList;


You can recursively loop through Master.Controls and check each control to see if it is of the type ContentPlaceHolder.

private readonly IList<ContentPlaceHolder> _contentPlaceHolders = new List<ContentPlaceHolder>();
private void FindContentPlaceHolders(ControlCollection controls)
{ 
    foreach(Control control in controls)
    {
        if (control is ContentPlaceHolder)
        {
            _contentPlaceHolders.Add((ContentPlaceHolder) control);
            return;
        }
        FindContentPlaceHolders(control.Controls);             
    }
}


As a variation to the answer of Daniel, you can write that as an extension method on MasterPage:

public static IEnumerable<ContentPlaceHolder>
    GetContentPlaceHolders(this MasterPage master)
{
    return GetAllControlsInHierarchy(master)
        .OfType<ContentPlaceHolder>();
}

private static IEnumerable<Control> GetAllControlsInHierarchy(
    Control control)
{
    foreach (var childControl in control.Controls)
    {
        yield return childControl;

        foreach (var childControl in
            GetAllControlsInHierarchy(childCOntrol))
        {
            yield return childControl;
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消