我需要显示一个列表视图,其中包含可变大小的列表,如下所示:
listview item1: Item1 Item2 Item3
listview item2: Item1 Item2
listview item2: Item1 Item2 Item3 Item4
等
有没有办法创建一个可以绑定到列表的自定义视图,所以我会像这样使用它:
<ViewCell>
<local:CustomView BindableProperty="{Binding listForThisCell}" />
</ViewCell>
我真的无法在任何地方找到合适的例子。
设法让它使用以下代码
namespace AppNamespace
{
public partial class ItemsView : StackLayout
{
public ItemsView()
{
InitializeComponent();
}
public static readonly BindableProperty ItemsListProperty =
BindableProperty.Create(nameof(ItemsList),
typeof(List<Item>),
typeof(ItemsView),
default(List<Item>));
public List<Item> ItemsList
{
get { return (List<Item>)GetValue(ItemsListProperty); }
set { SetValue(ItemsListProperty, value); }
}
protected override void OnPropertyChanged(string propertyName)
{
if (propertyName == ItemsListProperty.PropertyName)
{
foreach (Item comment in ItemsList)
{
Children.Add(new ItemView(comment));
}
}
base.OnPropertyChanged(propertyName);
}
}
}
XAML:
<?xml version="1.0" encoding="utf-8" ?>
<StackLayout xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="AppNamespace.ItemsView">
</StackLayout>
但是在OnPropertyChanged方法中添加子项是否可以?它应该在其他地方完成吗?
答案 0 :(得分:2)
您可以在BindableProperty
:
CustomView.cs
public static readonly BindableProperty ListForCurrentCellProperty =
BindableProperty.Create(nameof(ListForCurrentCell),
typeof(IList<object>),
typeof(CustomView),
default(IList<object>));
public IList<object> ListForCurrentCell
{
get { return (IList<object>)GetValue(ListForCurrentCellProperty); }
set { SetValue(ListForCurrentCellProperty, value); }
}
然后,您将能够从XAML绑定项目集合。