Reputation: 2284
I need to get the list of ContentPlaceHolders of a MasterPage, but the property
protected internal 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.
Upvotes: 1
Views: 911
Reputation: 172646
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;
}
}
}
Upvotes: 1
Reputation: 7969
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);
}
}
Upvotes: 2
Reputation: 172646
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;
Upvotes: 2