Xamarin.Forms使用LoadFromXaml加载Xaml不会为StackLayout创建包含的对象

问题描述 投票:0回答:1

我正在尝试将将动态生成的大量xaml添加到现有的xamarin.forms页面中。

我正在使用following example中的official docs开始研究。

[一切都很好,但是当我尝试使用按钮def更改字符串,而其中带有内部按钮的具有stacklayout的字符串时,只会使stacklayout膨胀,根本没有子代。

这很奇怪,因为您可以在示例中填充整页,但看起来我好像在这里漏了一些东西。

有关如何将LoadFromXaml用于部分组合对象的任何建议?

// MainPage.xaml.cs
void OnLoadButtonClicked(object sender, EventArgs e)
        {
            string navigationButtonXAML = "<StackLayout><Button Text=\"Navigate\" /></StackLayout>";
            var sl = new StackLayout().LoadFromXaml(navigationButtonXAML);
            _stackLayout.Children.Add(sl);
        }
xaml xamarin.forms
1个回答
0
投票

[从官方文档开始,它仅对单个视图或完整的contentPage使用LoadFromXaml,我也尝试对布局使用LoadFromXaml,并且它在没有其子级的情况下加载了布局。为了加载带有子级的布局,我尝试使用源代码进行调试,稍后将进行更新,作为一种解决方法,可以将布局与contentview一起使用,如下所示:

string navigationStackLayoutXAML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ContentView xmlns=\"http://xamarin.com/schemas/2014/forms\" xmlns:x=\"http://schemas.microsoft.com/winfx/2009/xaml\" xmlns:d=\"http://xamarin.com/schemas/2014/forms/design\" xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" mc:Ignorable=\"d\" x:Class=\"LoadRuntimeXAML.CustomerViewDemo\"> <ContentView.Content> <StackLayout > <Label Text=\"Hello Xamarin.Forms!\" /> <Button Text=\"SECONDB\"/> </StackLayout> </ContentView.Content> </ContentView>";
ContentView contentView = new ContentView().LoadFromXaml(navigationStackLayoutXAML);
_stackLayout.Children.Add(contentView);

虽然它的xaml有点复杂,但是它可以像.xaml中一样使用预定义的属性,而且contentView中的元素也可以通过以下方式访问:

Button secondB = contentView.FindByName<Button>("secondB");
    
© www.soinside.com 2019 - 2024. All rights reserved.