我想从另一个用户控件切换矩形的可见性。我相信我当前的代码不起作用,因为我正在创建第一个用户控件的新实例,其中我应该从旧的控件引用。不幸的是,我不知道如何参考。
用户控制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;
}
关注:
答案 0 :(得分:0)
用户控制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设置为oneUC变量。 在User Control 2构造函数中,您必须删除oneUC = new one(); 它会对你有用。
答案 1 :(得分:0)
脏版
创建一个可以访问所有用户控件的单例类,例如:
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;
}