Search code examples
c#androidmaui

MAUI: how to dynamically add Views to Page?


The problem I face is that I want to add Views (Entry, Button, Label etc...) dynamically into a Page, meaning that I don't know how many of each of them are to be displayed so I can't code them in directly into Xaml. I was thinking about creating an ObservableCollection list of Views in my viewmodel, add the views into the list and somehow bind them to a CollectionView in the xaml file to dynamically display each of them. But That did not work out (the code i tried):

<CollectionView ItemsSource="{Binding CustomFieldViews}">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <ContentView>
                <ContentView.Content>
                    <ContentPresenter Content="{Binding}" />
                </ContentView.Content>
            </ContentView>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

I have been struggling with this for a long time. It displays and works correctly in debug mode but not in release mode. Does anyone know how I can solve this problem? How can I dynamically add Views to a Page?


Solution

  • create a layout container for the Views

    <StackLayout ... x:Name="ViewContainer" />
    

    then dynamically create and add them to the container

    Button btn = new Button() { ... };
    ViewContainer.Children.Add(btn);