如何从后面的代码中在ListView \\的LayoutTemplate中设置用户控件的属性?
1 2 3 4 5
| <LayoutTemplate>
<myprefix:MyControl id="myControl" ... />
</LayoutTemplate>
...
</asp:ListView> |
我想这样做:
1
| myControl.SomeProperty = somevalue; |
请注意,我的控件不在ItemTemplate中,它不在LayoutTemplate中,因此并非所有项目都存在,它仅存在一次。因此,我应该能够访问一次,而不是针对每个数据绑定项。
1
| var control = (MyControl)myListView.FindControl("myControlId"); |
这将起作用,但是请确保在数据绑定之后执行此操作,否则将不会创建LayoutTemplate,从而引发错误。
要设置LayoutTemplate内部的控件的属性,只需使用ListView控件上的FindControl方法。
1
| var control = (MyControl)myListView.FindControl("myControlId"); |
此问题已在以下堆栈溢出问题中得到解答:
访问ListView
的LayoutTemplate内部的控件
请参阅tanathos对已接受答案的评论。
我知道这个问题是一年多以前问的,但这是我以前到这里来的搜索字词的第一个结果,所以我想把答案留给偶然发现它的任何人。
在每个ListViewItem上使用FindControl方法。
1
| var control = (MyControl)Item.FindControl("yourControlId"); |
如果您需要VB.net版本,则为:
1
| Dim control = CType(myListView.FindControl("myControlId"), MyControl) |
将创建布局,并触发一个LayoutCreated事件,该事件表明该布局已在系统中创建。
然后,您可以使用listview.FindControl获取对该控件的引用。