0
votes

I've created custom properties for my user controls.

My user control:

<asp:PlaceHolder ID="BtnPlaceHolder" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Button1" PostBackUrl="~/Page1.aspx"/>
    <asp:Button ID="Button2" runat="server" Text="Button2" PostBackUrl="~/Page2.aspx" />
</asp:PlaceHolder>

Property:

public bool ShouldBeVisible
{
    get
    {
        return Button1.Visible;
    }
    set
    {
        Button1.Visible = value;
    }
}

And in Page_Load:

protected void Page_Load(object sender, EventArgs e)
{
    Button1.Visible = ShouldBeVisible;
}

In page1.aspx using the UC:

<uc:MyUserControl runat="server" />

If I want to use the property on another button (eg. Button2), how can I re-use the ShouldBeVisible property?

EDIT: Sorry, but the ShouldBeVisible property I want to use on the Buttons, not the UC declaration. Depending on which page (page or page2) I want to show Button1 or Button2.

2
You mean you don't want return Button1.Visible but instead <uc:MyUserControl ID="MyUC" associatedControl="Button2" /> and then in code return AssociatedControl.Visible? - CodeCaster

2 Answers

1
votes

You can create the property of your UserControl in such a way so that it can be used for multiple controls not only for Button1. Here is one way to do this

private bool _shouldBeVisible = false;
public bool ShouldBeVisible
{
   get
   {
      return _shouldBeVisible;
   }
   set 
   {
      _shouldBeVisible = value;
   }
}

And then you can write something like this on your Page_Load of UC.

protected void Page_Load(object sender, EventArgs e)
{
   Button1.Visible = Button2.Visible = ShouldBeVisible;
}
0
votes

No need to introduce another property:

<uc:MyUserControl Visible="<%# Button1.Visible %>" />