如何在没有数据绑定的情况下从另一个用户控件访问控件?

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

我想从另一个用户控件切换矩形的可见性。我相信我当前的代码不起作用,因为我正在创建第一个用户控件的新实例,我应该在其中引用旧的。不幸的是,我不知道如何进行引用。

用户控件 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();
    }

用户控件 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;
    }

顾虑:

  1. 我知道这样做不是一个好的做法,但我只是使用 wpf 来创建这个非常简单的个人项目。做完这个小项目,wpf我也做完了。
  2. 没有数据绑定

用户控件 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();
    }

用户控件 2:

public two()
    {
        InitializeComponent();
    }

在用户控件 1 中,您需要创建用户控件 2 并将用户控件 1 设置到一个 UC 变量中。 在 User Control 2 构造函数中,您必须删除 oneUC = new one(); 它会为你工作。

脏版

创建一个可以访问所有用户控件的单例 class,例如:

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

在表单构造函数中(在 InitializeComponent() 之后)将您的控件分配给单例变量,如下所示:

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

然后在 UserControl2 中您可以执行以下操作:

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