Create Page Dynamically In Xamarin Form
i have a text file like this in the cloud i want to load this file and inject these codes in my
Solution 1:
If your xml file is not complex and you don't wanna use the Nuget package. Your own implementation should be fairly simple.
Assuming your xml file structure on cloud is like this:
<?xml version="1.0" encoding="utf-8" ?>
<Form>
<Entry Placeholder ="First Name" />
<Entry Placeholder ="Last Name" />
</Form>
Your Dynamic Page Template (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>
In the Code behind:
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);
}
}
}
Solution 2:
Take a look at the DynamicForms project on GitHub. It does exactly that by using the internal XamlLoader
class with reflection.
As to your use case, this is how it would work:
var page = new ContentPage();
string xaml = "<Entry Placeholder="FirstName />"; // Your example from the textfile
page.LoadFromXaml(xaml);
Here's also an article by the author of the library: Dynamic Xamarin.Forms from XAML and JSON.
Post a Comment for "Create Page Dynamically In Xamarin Form"