我想用MainMenu的网格中的按钮更改“ UserControl1”中按钮的文本。 “ UserControl1”是另一个UserControl(“ UserControl2”)中的网格的子代。 “ UserControl2”是MainWindow中网格的子级。
为了更好地理解:
MainWindow代码:
namespace UserControlTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
UserControl2 test = new UserControl2();
grd_Main.Children.Add(test);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
}
}
}
UserControl2代码:
namespace UserControlTest
{
public partial class UserControl2 : UserControl
{
public UserControl2()
{
InitializeComponent();
UserControl1 uc1 = new UserControl1();
grd_ParentOfUserControl1.Children.Add(uc1);
}
}
}
答案 0 :(得分:0)
Try this, i.e. you can get a reference to a UserControl
by casting the elements in the Grid
's Children
collection:
private void Button_Click(object sender, RoutedEventArgs e)
{
UserControl2 uc2 = grd_Main.Children.OfType<UserControl2>().FirstOrDefault();
if (uc2 != null)
{
UserControl1 uc1 = uc2.grd_ParentOfUserControl1.Children.OfType<UserControl1>().FirstOrDefault();
if (uc1 != null)
{
uc1.theButton.Content = "the text...";
}
}
}