我为项目ListView设置模板并分配列表项
listView.ItemTemplate = new DataTemplate(typeof(CustomVeggieCell));
listView.ItemsSource = posts;
如何在CustomVeggieCell中获取currentItem元素:
CustomVeggieCell.class:
public class CustomVeggieCell : ViewCell
{
public CustomVeggieCell(){
// for example int count = currentItem.Images.Count;
var postImage = new Image
{
Aspect = Aspect.AspectFill,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand
};
postImage.SetBinding(Image.SourceProperty, new Binding("Images[0]"));
var postImage = new Image
{
Aspect = Aspect.AspectFill,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand
};
postImage.SetBinding(Image.SourceProperty, new Binding("Images[1]"));
}
}
我想在ItemTemplate中获取大量图像.图像只是一个字符串列表.
附:我通过绑定获得ItemTemplate中的所有值.
最佳答案 要获取ItemTemplate中的当前项,您只需要引用CustomVeggieCell的BindContext,如下所示:
string imageString = (string)BindingContext; //Instead of string, you would put what ever type of object is in your 'posts' collection
话虽如此,你的代码对我来说并不完全有意义.如果您的CustomVeggieCell位于ListView中,则不需要通过硬编码项目的索引来访问项目列表,就像您在此处一样:
new Binding("Images[1]")
ListView应该基本上为你做所有项目的foreach.除非posts包含List< string>属性.
编辑:现在我对这个问题有了更好的了解.您可以在ViewCell上创建一个新的可绑定属性,并在OnPropertyChanged参数中指定一个方法,将图像添加到布局中,然后将布局添加到ViewCell.我从未尝试过这样的事情,所以这一切都可能根本不起作用.
就像是:
public class CustomVeggieCell : ViewCell
{
public List<ImageSource> Images {
get { return (ImageSource)GetValue(ImagesProperty); }
set { SetValue(ImagesProperty, value); }
}
public static readonly BindableProperty ImagesProperty = BindableProperty.Create("Images", typeof(List<ImageSource>), typeof(CustomVeggieCell), null, BindingMode.TwoWay, null, ImageCollectionChanged);
private StackLayout _rootStack;
public InputFieldContentView() {
_rootStack = new StackLayout {
Children = //Some other controls here if needed
};
View = _rootStack;
}
private static void ImageCollectionChanged(BindableObject bindable, object oldValue, object newValue) {
List<ImageSource> imageCollection = (List<ImageSource>)newValue;
foreach(ImageSource imageSource in imageCollection) {
(CustomVeggieCell)bindable)._rootStack.Children.Add(new Image { Source = imageSource });
}
}
}
或类似的东西.然后,您将posts.Images绑定到新的可绑定属性.我刚刚在文本框中编写了该代码,并且之前没有测试过类似的内容,但如果遇到问题,请告诉我.