0

我在页面上定义了 2 个用户控件:

<%@ Register Src="Foo.ascx" TagName="FooControl" TagPrefix="acme" %>
<%@ Register Src="Bar.ascx" TagName="BarControl" TagPrefix="acme" %>
.
.
.
<acme:FooControl ID="myFoo" runat="server" Visible="false" />
<acme:BarControl ID="myBar" runat="server" Visible="false" />

在运行时,我想在页面代码的不同位置设置用户控件的属性之一。例如:

protected void SomeMethod()
{
     if (isSomeCondition) 
     {
         myFoo.Visible = true;         
     }
     else
     {
         myBar.Visible = true;
     }

     // ...

     if (somethingElse) 
     {
         if (isSomeCondition) 
         {
             myFoo.Prop1 = 123;         
         }
         else
         {
             myBar.Prop1 = 123;
         }
     }

     // ...
}

我知道我可以让 2 个用户控件从一个通用接口继承,但是还有另一种(可能更好)的方法吗?

4

1 回答 1

1

编辑:我刚刚意识到我的大部分答案已经被对同一问题的评论所涵盖。向评论的人道歉,我不是故意“窃取”你的内容...... :)

不,我可以想出不同的方法来实现相同的结果(通过反射调用属性或使用FindControl解决问题),但我想不出比让两个控件实现相同的接口更好的方法。

然后,您可以通过另一个属性访问活动控件,例如:

public IMyControl ActiveControl 
{
  get 
  {
    return (isSomeCondition)? myFoo : myBar; 
  }
}
于 2013-01-17T15:56:22.730 回答