1

我遇到了一个奇怪的问题,对我来说没有任何意义。我正在尝试在页面上动态设置 MasterPage 内容控件。我让它与以下代码很好地工作:

    protected override void OnPreInit(EventArgs e)
    {
        base.OnPreInit(e);

        MasterPageFile = "~/MasterPages/Default.master";

        string existantContentPlaceHolderID = "ContentPlaceHolder1";
        string nonExistantContentPlaceHolderID = "foo";

        //Control c = Master.FindControl(existantContentPlaceHolderID);
        //Control c1 = Master.FindControl(nonExistantContentPlaceHolderID);

        TextBox t = new TextBox
                        {
                            Text = "Text"
                        };

        ITemplate iTemplate = new GenericITemplate(container => container.Controls.Add(t));

        AddContentTemplate(existantContentPlaceHolderID, iTemplate);

    }

    public delegate void InstantiateTemplateDelegate(Control container);

    public class GenericITemplate : ITemplate
    {
        private readonly InstantiateTemplateDelegate m_instantiateTemplate;

        public void InstantiateIn(Control container)
        {
            m_instantiateTemplate(container);
        }

        public GenericITemplate(InstantiateTemplateDelegate instantiateTemplate)
        {
            m_instantiateTemplate = instantiateTemplate;
        }
    }

这很好用,除了我希望能够在调用 AddContentTemplate 之前仔细检查 MasterPage 上是否存在 contentPlaceHolderID,因为如果添加指向不存在的 ContentPlaceHolder 的内容控件,页面将引发错误。

我遇到的问题是,在上面的示例中,当我调用注释的 Master.FindControl 行之一时,TextBox 不再呈现。

有没有人知道为什么会这样......我无法对正在发生的事情做出正面或反面。

谢谢,马克斯

4

1 回答 1

2

问题是 AddContentTemplate 只是将其参数记录在一个哈希表中,以便在创建时与母版页实例组合。在创建母版页后调用它不会做任何事情,读取 Master 属性会导致创建母版页。

我能看到的最好的方法是使用 LoadControl 创建一个单独的母版页实例,您可以在不影响页面自己的 Master 属性的情况下对其进行检查...

MasterPage testMaster = (MasterPage) LoadControl( MasterPageFile );
Control c = testMaster.FindControl(existantContentPlaceHolderID);

创建第二个实例有一些开销,但对我来说是否值得担心并不是很明显。

于 2008-10-29T15:27:50.403 回答