How to get the current item in ItemTemplate in Xamarin formats

I set a template for an item ListViewand assign list items

listView.ItemTemplate = new DataTemplate(typeof(CustomVeggieCell));  
listView.ItemsSource = posts;

How to get the item currentItemin CustomVeggieCell:

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]"));
        }
    }

I want to get the quantity Imagesin ItemTemplate. Imagesis just a list of strings.

ps All value in ItemTemplateI receive a binding.

+4
source share
1 answer

To get the current item in ItemTemplate, you only need to reference it CustomVeggieCell BindContextlike this:

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>.

: , . , bindable 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 bindable. , , .

+2

Source: https://habr.com/ru/post/1649758/


All Articles