[英]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:
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();。 它將為您工作。
臟版
創建一個可以訪問所有用戶控件的單例類,例如:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.