Search code examples
c#.netuser-controlsuwp-xaml

Accessing a button click of User Control in Parent page UWP


I have a user control created with name as UserControl.

This user control have a label and a button.

I use this user control in one of my page(lets say Page1), but this user control is generated based on the entries in DB. For eg: I have an entry in DB which has a column with name as 'UC1'. So on page(Page1) load, I dynamically add this usercontrol on the page.

Now when the page is loaded, I want the button click to method to be implemented in Page1 code behind. Could anyone let me know how is this possible. I am facing issue as the use control is dynamically generated and since multiple instances of usercontrols can be generated in the page based on the DB entries.

In short I want to call a method in code behind of parent page for the user control that is dynamically generated inside the parent page


Solution

  • Supposed the Button is named ‘btn1’, and the TextBlock named ‘textBlock1’, you can wire up like this

    for (int i = 0; i < 3; i++)
    {
        MyUserControl c = new MyUserControl();
        c.btn1.Click += (o, args) =>   
        {
            c.textBlock1.Text = DateTime.Now.ToString(); 
        };
    
        //then add the user control to the page
        this.stackPanel1.Children.Add(c);
    }
    

    And add an x:FieldModifier attribute to the elements so you can access them from outside.

    <Button x:Name=“btn1” x:FieldModifier=“public” ...