TonyW TonyW -4 years ago 106
Vb.net Question

Access controls on User Control

I have a user control, and I need to access a label on that user control from another Window.. example... simply change the text of a label. Example..

Usercontrol.label1.content = "Got it"


I can access any control on the MainWindow by doing the following:

Public main As MainWindow = DirectCast(Application.Current.MainWindow, MainWindow)


How do I do this for a User Control in WPF?

Answer Source

To access MainWindow:

Dim Main = TryCast(Application.Current.MainWindow, MainWindow);

If your UserControl defined statically like this:

<local:UserControl1 x:Name="uc" />

You can just use it's name like: Main.uc.label1.Text = "Hello World"

If your UserControl is dynamically added to a container, try following:

If your UserControl is in a Border:

Dim control = Main.MyBorder.Child as MyUserControl
control.label1.Text = "Hello World"

If there are multiple UserControls in your container such as (StackPanel/Grid/Wrappanel etc):

Dim controls = Main.MyStackPanel.Childern.OfType(Of MyUserControl)()
For Each control In controls
    control.label1.Text = "Hello World"
Next

Even though you can get the exact UserControl you want by checking the variables it has!

Dim control = Main.MyStackPanel.Childern.OfType(Of MyUserControl)().Where(Function(x) x.label1.Text = "myLabel").FirstOrDefault() 
//You can access any variable that exists in your UserControl by 'x'
control.label1.Text = "Hello World"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download