asp.net - 如何在运行时在 WebForms 中更改 UserControl 中控件的属性
问题描述
我有一个简单的 UserControl 定义为:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AdminBanner.ascx.cs" Inherits="OrderManager.Controls.AdminBanner" %>
<asp:Panel runat="server" ID="AlertPanel" BorderWidth="1px">
<asp:Label runat="server" ID="LabelTitle" Text="Test!!!!!!!" ></asp:Label>
</asp:Panel>
我在 aspx 页面上包含 UserControl,如下所示:
<table style="width: 100%;">
<tr>
<td>
<asp:Panel ID="PanelPreviewBanner" Visible="False" runat="server">
<OrderManager:AdminBanner Id="AdminBanner" Visible="True" runat="server" />
</asp:Panel>
</td>
</tr>
</table>
当我单击 Web 表单上的按钮时,我不仅要显示 Panel,还要更改 UserControl 中 LabelTitle 的默认值。我可以这样显示面板:
// Display the Preview Panel.
this.PanelPreviewBanner.Visible = true;
如果我尝试更改 USerControl 的 LabelTitle、使用 UC 的 ID 或通过 UserControl 中的属性更改,我总是会收到一条错误消息,指出该控件为空。
我的最终目标是能够在我的 UserControl 中定义的对象上设置 css 类和样式。
我已经尝试了很多我在这里和通过谷歌找到的例子,但没有任何效果。
解决方案
我假设你已经这样做了 -
- AdminBanner.ascx.cs 中的公共属性,公开标签的文本属性以由父页面设置
public string LabelTitleValue
{
get { return LabelTitle.Text; }
set { LabelTitle.Text = value; }
}
- 以下是您应该如何获取/设置用户控件的标签文本。
AdminBanner.LabelTitleValue = "Test changed";
var text = AdminBanner.LabelTitleValue;
如果您已经这样做了,您可以先尝试在面板外移除您的用户控件(如下所示),并至少确认正在显示用户控件。
<td>
<asp:Panel ID="PanelPreviewBanner" Visible="False" runat="server"></asp:Panel>
<OrderManager:AdminBanner Id="AdminBanner" Visible="True" runat="server" />
</td>
如果它显示正确,除了设置面板的可见性之外,您还可以执行以下操作
// Display the Preview Panel.
this.PanelPreviewBanner.Visible = true;
this.AdminBanner.Visible = true;
推荐阅读
- python - Python ElementTree myroot.findall()
- c# - Identity Server 4 v3.1.2 UserInteraction LoginUrl 不起作用
- java - 如何将字符串转换为 GUID
- python - 我可以将目录从 docker 区域外的某个位置复制到我的 dockerfile 吗?
- javascript - 仅使用纯 JavaScript 检查字符串是否为回文
- spring - 如何在 QuartzScheduler for Spring Framework 中配置 idleWaitTime 环境变量
- python-3.x - Visual Studio Code 单元测试环境
- c# - C#/.xaml WPF 页面出现问题,网格垂直扩展
- swift - 类方法中的 Swift 选项
- c# - 如何使用 It.IsAny AddItemFactory 函数模拟 IAppCache 的 GetOrAddAsync 方法