如何解决在Xamarin运行时使用ViewCells填充ListView
我正在尝试在运行时用自定义viewCell对象填充ListView,由于某种原因,Listview会使用ViewCell对象的类型字符串名称填充,而不是使用实际的ViewCell“填充”。
问:我需要做些什么才能使这些ViewCell“膨胀”,而不仅仅是显示其“ ToString()”输出?
以下是非常简单的MainPage.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="ViewCellExperiment.MainPage">
<StackLayout>
<ListView x:Name="mainListView"></ListView>
</StackLayout>
</ContentPage>
这是非常简单的MainPage.xaml.cs文件:
using System.Collections.Generic;
using Xamarin.Forms;
namespace ViewCellExperiment
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
var ListSource = new List<ViewCell>() { new CustomCell(),new CustomCell(),new CustomCell() };
mainListView.ItemsSource = ListSource;
}
}
}
最后是CustomCell.cs文件:
using Xamarin.Forms;
namespace ViewCellExperiment
{
public class CustomCell : ViewCell
{
public CustomCell()
{
StackLayout cellWrapper = new StackLayout();
StackLayout horizontalWrapper = new StackLayout();
Label explanatoryText = new Label() { Text = "Explanatory text Label" };
Button leftButton = new Button();
Button centerButton = new Button();
Button rightButton = new Button();
horizontalWrapper.Orientation = StackOrientation.Horizontal;
cellWrapper.Orientation = StackOrientation.Vertical;
leftButton.Text = "Record";
centerButton.Text = "Play";
rightButton.Text = "Upload";
horizontalWrapper.Children.Add(leftButton);
horizontalWrapper.Children.Add(centerButton);
horizontalWrapper.Children.Add(rightButton);
cellWrapper.Children.Add(explanatoryText);
cellWrapper.Children.Add(horizontalWrapper);
View = cellWrapper;
}
}
}
解决方法
您的自定义单元格应设置为DataTemplate
的{{1}},而不是ListView
。 ItemsSource
是一个模板化控件-您定义一个模板,并将该模板应用于ListView
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。