Xamarin.Forms在运行时加载XAML视图

时间:2018-02-13 14:25:07

标签: c# xaml xamarin xamarin.forms

我正在寻找一个在Xamarin.Forms中运行时动态加载XAML文件的解决方案,以便它可以显示为View / ContentPage。

我已经找到了这个问题的一些答案,但它们不再起作用或样本被删除了:

Xamarin forms.Dynamically load a page

https://forums.xamarin.com/discussion/87727/load-xaml-dynamically-at-runtime

要加载的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="Examples.Views.TestView">
    <ContentPage.Resources>
        <ResourceDictionary>
            <Style TargetType="Label">
                <Setter Property="FontSize" Value="Medium" />
                <Setter Property="TextColor" Value="Black"/>
            </Style>
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>
        <StackLayout>
            <Label Text="Hello World!"></Label>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

1 个答案:

答案 0 :(得分:4)

您应该可以使用LoadFromXaml extension method

使用以下方法添加: using Xamarin.Forms.Xaml;

然后像这样膨胀你的页面:

// TODO your XAML here
var xaml = "<ContentPage></ContentPage>";

var loadedXamlPage = new ContentPage();
loadedXamlPage.LoadFromXaml(xaml);

可以找到示例存储库here