2016-08-01 2 views
4

Я установил шаблон для элемента ListView и назначить пункты списка,Как получить текущий элемент в ItemTemplate в Xamarin Forms

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

Как получить currentItem элемент в 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]")); 
     } 
    } 

Я хочу получить сумму Images в ItemTemplate. Images - это просто список строк.

p.s. Все значение в ItemTemplate Я получаю привязку.

ответ

2

Чтобы получить текущий элемент в ItemTemplate вам только нужно ссылаться на CustomVeggieCell «s 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>.

Редактировать: Теперь, когда у меня есть лучшее понимание проблемы. Вы можете создать новое свойство 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. Снова я написал этот код только сейчас в текстовом поле и раньше не тестировал ничего подобного, но дайте мне знать, если у вас возникнут проблемы.

+1

Благодарим за ответ. Но BindingContext всегда имеет значение null, когда я пытался получить var allModel = BindingContext как WallPostViewModel; или var images = (IList ) BindingContext; В любом случае значение и BindingContext имеют значение null ... –

+0

@IgorLevkivskiy 'CustomVeggieCell.BindingContext' останется' null', пока 'ListView' не заполнит' CustomVeggieCell', и данные будут показаны на экране. Попытайтесь объяснить, что вы пытаетесь сделать с помощью CustomVeggieCell.BindingContext, и, возможно, мы сможем вам помочь. – hvaughan3

+0

Я хочу получать изображения из currentItem, потому что у каждого сообщения есть разные количества фотографий, поэтому я хочу отображать разные количества фотографий для currentItem, используя разные макеты. –

Смежные вопросы