如何启用/禁用一组控件?

时间:2011-10-21 21:38:17

标签: c# asp.net user-controls

我的规格要求下拉或两个日历框旁边的单选按钮组来控制哪个是活动的,所以我做了这个用户控件:

<asp:RadioButton 
    GroupName="group1" 
    ID="DateMacroRadioButton" 
    runat="server" 
    Checked="true" />
<uc:DateMacroSelector ID="DateMacroSelector1" runat="server" />
<asp:RadioButton GroupName="group1" 
    ID="CustomDateRadioButton" 
    runat="server" 
    AutoPostBack="true" Text="" />
<uc:DateSelector ID="DateSelector1" runat="server" />
to
<uc:DateSelector ID="DateSelector1" runat="server" />

enter image description here

我想使用组启用/禁用子控件:

<asp:RadioButton 
    GroupName="group1" 
    ID="DateMacroRadioButton" 
    runat="server"  
    Checked="true" />
<uc:EnableGroup ID="EnableGroup1" runat="server"
   CheckBoxId="DateMacroRadioButton">
   <uc:DateMacroSelector ID="DateMacroSelector1" runat="server" />
</uc:EnableGroup>
<asp:RadioButton GroupName="group1" 
    ID="CustomDateRadioButton" 
    runat="server" 
    AutoPostBack="true" Text="" />
<uc:EnableGroup ID="EnableGroup12 runat="server" 
    CheckBoxId="CustomDateRadioButton">
   <uc:DateSelector ID="DateSelector1" runat="server" />
   to
   <uc:DateSelector ID="DateSelector1" runat="server" />
</uc:EnableGroup>

我如何设计以这种方式工作的用户控件?

1 个答案:

答案 0 :(得分:1)

你可以创建一个自定义控件,这样的东西应该工作(获得“parsechildren”设置让它在设计器中工作总是令人讨厌,但我认为这是正确的):

[ParseChildren(typeof(WebControl), ChildrenAsProperties = true, 
    DefaultProperty = "ChildControls"), NonVisualControl]
public class EnableGroup: Control
{
        public EnableGroup() {
             ChildControls = new Collection<WebControl>();
        }

        protected override void OnPreRender(EventArgs e)
        {
            foreach (WebControl ctl in Controls) {
                ctl.Enabled = this.Enabled;
            }
            base.OnPreRender(e);
        }

        public Collection<WebControl> ChildControls
        {
            get; 
            protected set;
        } 
}

但老实说,简单地编写扩展方法或其他东西可能同样容易,例如。

public static SetChildEnabled(this WebControl parent) {
    foreach (WebControl ctl in parent.Controls) {
         ctl.Enabled = parent.Enabled;
    }
}

然后只需使用任何旧控件来包装你的组......

<asp:PlaceHolder runat="server" id="Group1">
</asp:PlaceHolder>

并在prerender上调用该代码:

Group1.SetChildEnabled()

如果需要,您可以非常轻松地递归地处理更深层次的嵌套子项。

想想看,你可以创建一个扩展PlaceHolder的控件并跳过上面的难点...如果你想能够控制容器中允许的对象类型,那就是你是怎么做到的,但可能有点矫枉过正。