Search code examples
buttonxamarin.formscode-behindcontent-pages

How can I add a button inside var content page code-behind using Xamarin.Forms?


How can I add a button inside var content page in code-behind? I'm trying to make a list view of content pages each with its own button.

var content = new ContentPage
              {
                   Title = EntryTitulo.Text,
                   Content = new Label
                   {
                       Text = EntryText.Text,
                       VerticalOptions = LayoutOptions.CenterAndExpand,
                       HorizontalOptions = LayoutOptions.CenterAndExpand,                       
                    },

                    //I want to add a button here.... 
               };

Solution

  • A ContentPage can only have a single child. If you want to add multiple children, they need to be contained in a Layout container, like a StackLayout or a Grid

    var label = new Label { ... };
    var button = new Button { ... };
    
    var layout = new StackLayout();
    
    layout.Children.Add(label);
    layout.Children.Add(button);
    
    Content = layout;