我在云端有一个这样的文本文件
<Entry Placeholder ="FirstName" />
<Entry Placeholder ="Last Name" />
我想加载此文件并在运行时以Xamarin表单的形式在我的内容页面中注入这些代码
答案 0 :(得分:2)
查看GitHub上的DynamicForms项目。它通过使用带有反射的内部XamlLoader
类来实现这一点。
关于您的用例,这就是它的工作原理:
var page = new ContentPage();
string xaml = "<Entry Placeholder="FirstName />"; // Your example from the textfile
page.LoadFromXaml(xaml);
以下是图书馆作者的一篇文章:Dynamic Xamarin.Forms from XAML and JSON。
答案 1 :(得分:1)
如果您的xml文件不复杂,并且您不想使用Nuget包。你自己的实现应该相当简单。
假设云上的xml文件结构是这样的:
<?xml version="1.0" encoding="utf-8" ?>
<Form>
<Entry Placeholder ="First Name" />
<Entry Placeholder ="Last Name" />
</Form>
您的动态页面模板(YourForm.Xaml):
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Company.Project.Feature.Views.YourForm">
<StackLayout Spacing="6" x:Name="EntryFieldsStack">
<!--Currently this is empty. Children are added in the code behing after loading the xml file from the cloud-->
</StackLayout>
</ContentPage>
在守则背后:
namespace Company.Project.Feature.Views
{
public partial class YourForm:ContentPage
{
InitializeComponent();
LoadDynamicFields();
}
public void LoadDynamicFields()
{
//load the file as an XDocument from the url
var doc = System.Xml.Linq.XDocument.Load("http://example.com/xml-file-url");
foreach (var entry in doc.Descendants("Entry")
.Select(e => new Entry {Placeholder = e.Attribute("PlaceHolder")?.Value}))
{
EntryFieldsStack.Children.Add(entry);
}
}
}