1

I have a Xamarin.Forms application which calls the backend. The backend gives a list of items. These items all have a type and a description. Based on the type, I need to decide what view element I need to create (entry, label, picker, checkbox etc..). Also the description should probably be a label, each view has it's own description.

How can I achieve this? I really have a hard time figuring this out..

Example: the backend gives a list with two objects. First object has phonenumer has a type, second element has a boolean as a type. The firstone should just create an entry and the second one should create a picker. Both rows/views should have a description, that could be just a label.

M Yil
  • 877
  • 1
  • 14
  • 35
  • You can use a StackLayout and create the Views in the code behind file. https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/get-started-with-xaml?tabs=macos – Nikhil Mar 20 '20 at 10:37
  • So, looping thoruhg the list, creating the view and adding that to the stacklayout? Will this work? – M Yil Mar 20 '20 at 10:45
  • Yes, but the StackLayout should be present in ContentPage.Content. My suggestion would be, if you have only 4-5 combinations of views you can write the methods and be ready and looping through the list you can just keep on calling the needed methods. – Nikhil Mar 20 '20 at 10:47
  • Hmm, oke I will try! Thank you. – M Yil Mar 20 '20 at 10:49
  • 1
    Most Welcome! Let me know if you have further queries. – Nikhil Mar 20 '20 at 11:16
  • Allright, I created the fields dynamically from the code behind by looping through a list of objects. But now I need to bind it to the appropriate property in the list where I looped over.. normally when using a listview binding becomes easy, but how can i bind each view with the appropriate element in the list in the viewmodel.. Hmm – M Yil Mar 20 '20 at 12:48
  • You can refer this link to set the bindings in code. https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/basic-bindings. – Nikhil Mar 20 '20 at 14:50

1 Answers1

1

You could use a Bindable Layout (https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/layouts/bindable-layouts) with a DataTemplateSelector (https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/templates/data-templates/selector) that provides the according DataTemplate depending on the Type of the object you receive.

On the XAML for each DataTemplate you can do the bindings (https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-binding-basics)

This way you don't have to code anything in code-behind nor loop over anything, because the Bindable Layout will do it for you and decide what to show depending on what object it received.

Miguel
  • 143
  • 1
  • 7