none
[UWP]Accessing a button click of User Control in Parent page UWP

    Question

  • 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



    Wednesday, November 21, 2018 1:23 PM

All replies

  • Hello Aswin M,

    Supposing the button in your user control has the Name "TheButton",

    <Button x:Name="TheButton" Content="Don't click"/>

    define a custom event to make the Button.Click publicly-accessible.

        public sealed partial class YourUserControl : UserControl
        {
            public event RoutedEventHandler ButtonClick
            {
                add { TheButton.Click += value; }
                remove { TheButton.Click -= value; }
            }
    
            public YourUserControl()
            {
                this.InitializeComponent();
                //this.DataContext = this; } }

    Then, you'll be able to register Click event handler in the parent page.

                var control_instance = new YourUserControl();
                control_instance.ButtonClick += YourUserControl_ButtonClick;


    Thursday, November 22, 2018 12:39 AM
  • Hi,

    Does @FEC-4RP's reply solve the problem?

    Is there any other questions?

    Best regards,

    Roy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, December 6, 2018 10:08 AM
    Moderator