Forum Xamarin.Forms

Generate/Display Controls Dynamically in Xamarin Forms

Hi Everyone,

I recently started learning Xamarin (MVVM). I am basically trying to convert a traditional Xamrin app to Xamarin Forms (MVVM). I need to remove all the code from code-behind and implement MVVM architecture. I have List objects(some types). I am populating that list using a picker. My task is generate dynamic controls(UI) based on picker selection. For example, if I select type-a in the picker, the stacklayout below the picker should have four entries and 2 switches, if type-b is selected, the stacklayout should display five other controls. In general I need the functionality that generates/displays controls dynamically depending on the type of selection made from picker. I can perform this in code-behind, I add the children to the stacklayout depending on the type selected. Now I need to move this functionality to Forms and get the same done using Xaml.

Can anyone please help me with this?

Thanks a lot in advanced!

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai

    I suggest creating several content views on your content page. Then define some properties in the view model binding to the IsVisible property of the content views. Therefore, they could decide which content view should be displayed.
    When the SelectedIndex of the Picker has been changed, change the value of the property. At last, it could inform the page part to display the expected content view.

  • deepsojitradeepsojitra Member

    @LandLu thank you for your response.

    I liked your idea to hide/show the content view. However, do you think there's an option to dynamically add children to the stacklayout so that content view doesn't need to render the view every time. I can do MyStackLayout.Children.Add() in code-behind, I would like to achieve the same using Xaml on the Xamarin Forms.

    Thanks again!

  • LandLuLandLu Member, Xamarin Team Xamurai

    If we place a control in the view architecture it means MyStackLayout.Children.Add() in the code-behind.
    Normally, we could predefine several views in Xaml with IsVisible to false. This won't occupy too many resources to render the controls. And then we could display them through changing the property in the corresponding view model like this approach:
    https://stackoverflow.com/a/42306777/8354952

Sign In or Register to comment.