如何动态访问用户控件属性?

发布于 2024-08-25 14:14:48 字数 486 浏览 4 评论 0原文

我试图创建一个“用户控制菜单”,其中页面用户控件的链接放置在页面顶部。这将允许我在页面上放置多个用户控件,并允许用户跳转到页面的该部分,而无需滚动太多。为了做到这一点,我将每个用户控件放在一个文件夹(用户控件)中,并为每个控件提供一个描述属性(<%@ Control Language="C#" Description = "Vehicles" .... %>< /代码>)。

我的问题是如何动态访问此描述?我想使用此描述作为我的菜单中的链接。到目前为止,我的页面上有一个 foreach,它在 ControlCollection 中查找 ASP.usercontrols 类型的控件。如果是的话,我会假设我可以访问它的属性并获取该描述属性。我该怎么做? (我也愿意以更好的方式实现我的“用户控制菜单”,但也许这是另一个问题。)我应该使用 ((System.Web.UI.UserControl)mydynamiccontrol).Attributes.Keys

Im trying to create a "user control menu" where links to a page's usercontrols are placed at the top of the page. This will allow me to put several usercontrols on a page and allow the user to jump to that section of the page without scrolling so much. In order to do this, I put each usercontrol in a folder (usercontrols) and gave each control a Description property (<%@ Control Language="C#" Description = "Vehicles" .... %>).

My question is how can I access this description dynamically? I want to use this description as the link in my menu. So far, I have a foreach on my page that looks in the ControlCollection for a control that is of the ASP.usercontrols type. If it is I would assume that I could access its attributes and grab that description property. How can I do this? (Im also open to a better way to achieve my "user control menu", but maybe thats another question.) Should I use ((System.Web.UI.UserControl)mydynamiccontrol).Attributes.Keys?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尽揽少女心 2024-09-01 14:14:48

您可以迭代集合并执行 switch 或一些 if 语句

我建议您为所有用户控件提供一个接口或抽象基类:

public abstract class MyBaseClass : UserControl
{
  public abstract string MyDescription {get;}
}

public MyUserControlA : MyBaseClass
{
  public string MyDescription {get {return "my description";}}
}

public MyUserControlB : MyBaseClass
{
  public string MyDescription {get {return "my other description";}}
}

然后您可以像您一样循环它们:

foreach ...
if (mydynamiccontrol is MyBaseClass)
{
    Response.Write(((MyBaseClass)mydynamiccontrol).MyDescription);
}

希望这有帮助

you can iterate over the collection and do either a switch or a few if statements

I would suggst you have an interface or an abstract base class for all your user controls:

public abstract class MyBaseClass : UserControl
{
  public abstract string MyDescription {get;}
}

public MyUserControlA : MyBaseClass
{
  public string MyDescription {get {return "my description";}}
}

public MyUserControlB : MyBaseClass
{
  public string MyDescription {get {return "my other description";}}
}

Then you can loop over them as you do:

foreach ...
if (mydynamiccontrol is MyBaseClass)
{
    Response.Write(((MyBaseClass)mydynamiccontrol).MyDescription);
}

Hope this helps

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文