Search code examples
c#wpfuser-interfaceuser-controls

WPF C# How do i change the Text of a Button that is in a UserControl in another UserControl?


I want to change the Text of a Button in my "UserControl1" with a Button in my MainMenu's Grid. "UserControl1" is a Children of a Grid that is in another UserControl("UserControl2"). The "UserControl2" is a Child of a Grid that is in the MainWindow.

For better understanding:

MainWindow Code:

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 Code:

namespace UserControlTest
{
    public partial class UserControl2 : UserControl
    {
        public UserControl2()
        {
            InitializeComponent();

            UserControl1 uc1 = new UserControl1();

            grd_ParentOfUserControl1.Children.Add(uc1);
        }
    }
}

Solution

  • 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...";
            }
        }
    }