Issue
I want to fetch the XML Entry Control from API, available in JSON.
All the attributes for Entry control are in JSON. I want to add them in .xml
page and get their values (when user enter in app) in ViewModel
(through data binding).
UPDATE
Update the Code according to the answer.
public partial class FormPage : ContentPage, IRootView
{
public List<Form> forms { get; set; }
public class RootObject
{
public bool success { get; set; }
public Datum[] data { get; set; }
}
public class Datum
{
public Form[] form { get; set; }
}
public class Form
{
public string label { get; set; }
public string name { get; set; }
public string type { get; set; }
public int max_length { get; set; }
public bool required { get; set; }
}
public FormPage()
{
InitializeComponent();
var json = @{};
var list = JsonConvert.DeserializeObject<RootObject>(json);
forms = new List<Form>();
forms = list.data.FirstOrDefault().form.ToList();
this.BindingContext = this;
}
}
Solution
Deserialize Json: Install Newtonsoft.Json
from NuGet.
Convert the json to classes and then get the list of the json data.
In your VS, Edit> Paste Special> Paste JSON As Classes
public class Rootobject
{
public bool success { get; set; }
public Datum[] data { get; set; }
}
public class Datum
{
public Form[] form { get; set; }
}
public class Form
{
public string label { get; set; }
public string name { get; set; }
public string type { get; set; }
public int max_length { get; set; }
public bool required { get; set; }
}
Deserialize to get the list:
var list = JsonConvert.DeserializeObject<Rootobject>(json);
Use the Bindablelayout.ItemTemplate of StackLayout to setup the template of Entry:
Xaml:
<StackLayout x:Name="DynamicEntry" BindableLayout.ItemsSource="{Binding forms}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Entry Placeholder="{Binding label}" MaxLength="{Binding max_length}" />
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
Code behind:
public List<Form> forms { get; set; }
public Page1()
{
InitializeComponent();
var json = @"{
'success': 'true',
'data': [
{
'form': [
{
'label': 'Name',
'name': 'name',
'type': 'text',
'max_length': '15',
'required': 'true'
},
{
'label': 'Email',
'name': 'email',
'type': 'email',
'max_length': '30',
'required': 'true'
}
]
}
]
}";
var list = JsonConvert.DeserializeObject<Rootobject>(json);
forms = new List<Form>();
forms = list.data.FirstOrDefault().form.ToList();
this.BindingContext = this;
}
Please note if you want to set the Kayboard with different types, you need convert the list with Keyboard class.
Answered By - Wendy Zang - MSFT
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.