[英]How to handle the Click event of a button in a custom ITemplate control?
I've created a custom control in ASP.NET for showing a pop-up message box. 我已经在ASP.NET中创建了一个自定义控件,用于显示弹出消息框。 In my MessageBox class, I have a Content property as ITemplate like the following: 在我的MessageBox类中,我有一个Content属性,如ITemplate,如下所示:
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateContainer(typeof(MessageBoxContent))]
[TemplateInstance(TemplateInstance.Single)]
public ITemplate Content { get; set; }
I used my custom control in my page like this: 我在页面中使用了自定义控件,如下所示:
<cc1:MessageBox ID="MessageBox1" runat="server">
<Content>
<asp:Button Text="Save" runat="server" ID="B_Save" />
</Content>
</cc1:MessageBox>
Even I set the the Content property's TemplateInstance to Single, I still can't have access to the Button control. 即使将Content属性的TemplateInstance设置为Single,我仍然无法访问Button控件。
All I want to do is to handle the click event of the button. 我要做的就是处理按钮的click事件。 When I assign an event handler to the button control and run the project, it throws a NullReferenceException. 当我将事件处理程序分配给按钮控件并运行项目时,它将引发NullReferenceException。 Is there a way to handle this issue? 有没有办法解决这个问题?
I had a similar problem in a custom control I created. 我在创建的自定义控件中遇到了类似的问题。
I wanted to find a LinkButton within the Itemplate Template property and assign a Click Event to it. 我想在Itemplate模板属性中找到一个LinkButton并将一个Click Event分配给它。
I was instantiating the template in OnInit and assigning the click event in OnLoad . 我在OnInit中实例化了模板,并在OnLoad中分配了click事件。
I found the LinkButton in OnLoad , no problem. 我在OnLoad中找到了LinkButton,没问题。 I was also able to add the Click event which all seemed fine until, when I tried to click the LinkButton, the Click event was not firing. 我还能够添加Click事件,这些事件似乎都还不错,直到尝试单击LinkButton时,Click事件都没有触发。
The fix for me was to make my custom control implement INamingContainer . 对我来说,解决方法是使我的自定义控件实现INamingContainer 。
It depends on when you're calling the template instantiation. 这取决于您何时调用模板实例化。
You shold be doing that during container's Load event, and you'll get access to template-injected controls just after calling ITemplate.InstantiateIn method. 您可以在容器的Load事件期间执行此操作,然后只需调用ITemplate.InstantiateIn方法即可访问注入模板的控件。
If you don't have access to the control, it should be you're looking in a wrong control hierarchy level. 如果您无权访问该控件,则可能是您正在寻找错误的控件层次结构级别。 Maybe you're nesting it in the wrong place? 也许您将其嵌套在错误的位置?
Can you give us a part of your source code? 您能给我们一部分源代码吗? It could be good to see where you instantiate your control template and later, where you try to add a Click event handler. 这可能是不错的,看看你实例化你的控制模板以后,您尝试添加一个Click事件处理程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.