简体   繁体   中英

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

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.

Dirty Version

Create a singleton class that will have access to all User Controls, eg.:

public static class Container 
{
    public static UserControl1 Control1 {get;set;}
    public static UserControl2 Control2 {get;set;}
}

In form constructor (after InitializeComponent()) assing your controls to singleton variables like this:

Container.Control1 = control1;
Container.Control2 = control2;

Then in UserControl2 you can do following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM