Search code examples
c#xamarin.formsxamarin.android

XAMARIN How to use the event handler of a button that has been created by another button


So i've made a program that has an "Add to favourite" button (a favourite color) so i select a color and when i click the "Add" button it goes to the event handler (pressed) and creates a new button with this code :

        Frame frame;
        private void OnAdd(object sender, EventArgs e)
        { 
               parent.Children.Add(frame = new Frame
                {
                    BorderColor = Color.Black,
                    Padding = new Thickness(5),
                    Content = new StackLayout
                    {
                        Orientation = StackOrientation.Horizontal,
                        Children =
                        {
                            new Button
                            {
                                Text="btn",

                            },
                            new Label
                            {
                                Text ="sample text", FontSize=Device.GetNamedSize(NamedSize.Large, typeof(Label)),
                                VerticalOptions = LayoutOptions.Center
                            }
                        }
                    }
                });
         }

the thing is i want to detect if those created buttons are pressed too so i can code in their own eventHandler.

Btw, it isn't about the colors (it's just to illustrate the thing) but more about the "Add to favourite" system.

Thanks in advance :))


Solution

  • Just set he eventHandler is OK.

    ........your code
    new Button
      {
          Text="btn",
    
      }
    ......
    

    it should changed to:

    var button=new Button{Text="btn"};
    button.Click=OnAdd;
    

    and then make this button to your frame.