如何解决在 Xamarin 中动态添加入口控制
我想从 API 获取 XML Entry Control,在 JSON 中可用。
Entry 控制的所有属性都在 JSON 中。我想将它们添加到 .xml
页面中,并在 viewmodel
(通过数据绑定)中获取它们的值(当用户进入应用程序时)。
更新
根据答案更新代码。
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;
}
}
解决方法
反序列化 Json:从 NuGet 安装 Newtonsoft.Json
。
将json转成class,然后得到json数据列表。
在你的 VS 中,编辑>选择性粘贴>将 JSON 粘贴为类
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; }
}
反序列化以获取列表:
var list = JsonConvert.DeserializeObject<Rootobject>(json);
使用StackLayout的Bindablelayout.ItemTemplate设置Entry的模板:
XML:
<StackLayout x:Name="DynamicEntry" BindableLayout.ItemsSource="{Binding forms}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Entry Placeholder="{Binding label}" MaxLength="{Binding max_length}" />
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
背后的代码:
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;
}
请注意,如果您想设置不同类型的 Kayboard,您需要使用 Keyboard 类转换列表。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。