Xamarin.Forms - 需要有一个接受多个视图的自定义控件



我需要有一个自定义视图,该视图将接受多个视图,然后根据需要显示不同的视图。我使用类文件创建了一个自定义视图,并且创建了如下所示的IList<View>的公共属性。

public class CustomLayout : ContentView
{
private IList<View> _childViews = new List<View>();
public IList<View> ChildViews 
{ 
get { return _childViews; } set { _childViews = value; } 
}
public CustomLayout()
{
//If 'ChildViews' count is greater than 0 then process views 
//and have a custom view as Content.
}
}

现在我的 xaml 看起来像这样

<controls:CustomLayout BackgroundColor="Pink" HorizontalOptions="FillAndExpand">
<controls:CustomLayout.ChildViews>
<Frame Height="50" Width="50" BackgroundColor="Yellow"/>
<Frame Height="50" Width="50" BackgroundColor="Green"/>
<Frame Height="50" Width="50" BackgroundColor="Red"/>
<Frame Height="50" Width="50" BackgroundColor="Blue"/>
</controls:CustomLayout.ChildViews>
</controls:CustomLayout>

现在我面临的问题是,当调用 ctorCustomLayout时,我没有得到"ChildViews"的"设置"调用,也没有获得"ChildViews"中的所有视图。 我也尝试为"ChildViews"创建BindableProperty,但存在相同的行为。 一件非常奇怪的事情是,几天前我正在尝试同样的事情,并且我得到了一个关于CustomLayout的视图列表。当时我不得不恢复代码,现在我不记得代码中有什么,所以它当时可以工作。

哈哈。

编辑:

对于不完整的问题,我真的很抱歉。通过查看评论和答案,我觉得我需要解释为什么我需要"ChildViews"而不是TemplateSelector

我需要创建一个像FlexLayout这样的自定义布局,因此我需要属性"ChildViews"访问的所有子项。我将在同一类中编写自定义逻辑,该逻辑将根据宽度将所有"ChildViews"放置在StackLayout中。

为什么我不使用FlexLayout?flexlayout 中存在一个问题,该问题已报告此问题。因此,我需要创建自定义布局。

如果您有更好的方法,那么也请提出建议。!

就像ToolmakerSteve说的那样,你可以使用DataTemplateSelector

一个简单的例子供您参考:

class DymaicDataTemplateSelector : DataTemplateSelector
{
public DataTemplate Tab1Template { get; set; }
public DataTemplate Tab2Template { get; set; }
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
return ((TabViewModel)item).Header == "Tab1" ? Tab1Template : Tab2Template;
}
}

对于整个项目,您可以参考下面的链接。加载内容在轮播中查看 Xamarn 窗体中的视图

有关更多详细信息,您可以查看 MS 文档。 https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/templates/data-templates/selector

最新更新