itzgeez
itzgeez

Reputation: 49

How do I access a particular control within a user control?

Let's say I have a user control with some controls inside of it, and I make this user control visible inside of a form. How do I access a particular control within that user control? For example, before, if I had a label inside of a form, all I did was label.Text = "text"; but how would I change the text of a label (just for example) which is inside of a user control which is inside of a form?

Upvotes: 1

Views: 1987

Answers (2)

nmvision
nmvision

Reputation: 89

I'm not exactly sure of your context, so here's a solution from my interpretation:

Usually User Controls are used when you have a large number of the same type of UIElement. I might add all of these to a Stack Panel for example. If I have a public ID in the User Control Class, I can look for that particular ID and modify its text.

MyUserControl.xaml.cs :

//ATextBox is a named Control
public MyUserControl(int ID)
{
    InitializeComponent();
    this.ID = ID;
    ATextBox.Text = "Something";
}

MainWindow.xaml.cs :

//MyStackPanel is a named Control
foreach (MyUserControl muc in MyStackPanel.Children)
{
    //ID is public get, private set
    if(muc.ID == 123456)
    {
        muc.ATextBox.Text = "Something Else";
    }
}

I'm taking some liberties with how I could setup the permissions etc, but hopefully this illustrates one way you might do it. Alternatively, if the user is interacting directly with the User Control, then you could set up the logic right inside the User Control Class.

Upvotes: 0

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34180

Create a public method in your user control and call it from form:

public void SetCaption(string caption)
{
    label1.Text = caption;
}

now in your form:

userControl1.SetCaption("text");

To access the control itself as you suggested in the comments, you can create a public property in your usercontrol that returns the control you want:

public Label MyLabel {get { return Label1; }}

and then in your form:

userControl1.MyLabel.Text = "text";

Upvotes: 2

Related Questions