Devon Mccoy Devon Mccoy -3 years ago 61
C# Question

How to access controls from another user control without data binding?

I want to toggle a rectangle's visibility from another user control. I believe my current code isn't working because I'm creating a new instance of the first user control wherein I should be referencing from the old one instead. Unfortunately, I don't know how to make that reference.

User Control 1:

public one()
{
InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
Window window = new Window
{
Title = "Second User Control",
Content = new two(),
WindowStartupLocation = WindowStartupLocation.CenterScreen,
ResizeMode = ResizeMode.NoResize
};
window.ShowDialog();
}


User Control 2:

one oneUC;
public two()
{
InitializeComponent();
oneUC = new one();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
oneUC.rectangleControl.Visibility = Visibility.Hidden;
}

private void Button_Click_1(object sender, RoutedEventArgs e)
{
oneUC.rectangleControl.Visibility = Visibility.Visible;
}


Concerns:


  1. I understand it's not a good practice to do this but I'm only using wpf to create this very simple personal project. After this small project is done, I'm done with wpf as well.

  2. Without data binding


Answer Source

User Control 1:

private void Button_Click(object sender, RoutedEventArgs e)
    {
    two tw = new two();
    tw.oneUC = this;
        Window window = new Window
        {
            Title = "Second User Control",
            Content = tw,
            WindowStartupLocation = WindowStartupLocation.CenterScreen,
            ResizeMode = ResizeMode.NoResize
        };
        window.ShowDialog();
    }

User Control 2:

public two()
    {
        InitializeComponent();
    }

In User Control 1 you need create User Control 2 and set User Control 1 into oneUC variable. In User Control 2 constructor you have to remove oneUC = new one(); It will work for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download