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

3
我正在寻找一种解决方案,在Xamarin.Forms中动态加载XAML文件,以便将其显示为视图/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>

您是否正在寻找从网站(或类似站点)动态下载这些页面的方法?如果您使用 WebView,解决方案是否会更简单? - Neil
我正在从 Web 服务下载这些文件,以便在运行时进行编辑。由于我在 XAML 中使用了绑定,所以我不确定 WebView 是否适用于我的情况。 - gh0stc0de
1个回答

6
你应该能够使用扩展方法LoadFromXaml
添加以下using语句:using Xamarin.Forms.Xaml; 然后按照以下方式填充你的页面:
// TODO your XAML here
var xaml = "<ContentPage></ContentPage>";

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

一个示例存储库可以在这里找到。

非常感谢您快速回答并提供解决方案。我之前尝试过同样的方法,但没有成功。但是通过您提供的示例项目,我成功找到了我的解决方案中的错误。我只需要移除Xamarin.Forms.Dynamic NuGet,并将Xamarin.Forms NuGet更新至最新版本(2.5.0)即可。 现在它完美地运行了! - gh0stc0de

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接