2015-03-28 3 views
0

У меня есть Xamarin Forms ListView настроить как этотПолучение содержимого из ListView

public class AddressView : ContentPage 
{ 
    public AddressView() 
    { 
     this.Title = "Native address book"; 
     CreateView(); 
    } 

    async void CreateView() 
    { 
     IAddress addresses = DependencyService.Get<IAddress>(); 
     var addressList = addresses.ContactDetails(); 
     if (addressList.Count == 0) 
     { 
      await DisplayAlert("No contacts", "Your phone has no contacts stored on it", "OK"); 
      return; 
     } 

     if (Device.OS != TargetPlatform.iOS) 
      BackgroundColor = Color.White; 
     else 
      Padding = new Thickness(0, 20, 0, 0); 

     var myList = new ListView() 
     { 
      ItemsSource = addressList, 
      ItemTemplate = new DataTemplate(typeof(MyLayout)) 
     }; 
     myList.ItemSelected += MyList_ItemSelected; 

     Content = myList; 
    } 

    void MyList_ItemSelected (object sender, SelectedItemChangedEventArgs e) 
    { 
     var item = e.SelectedItem as ViewCell; 
    } 
} 

public class MyLayout : ViewCell 
{ 
    public MyLayout() 
    { 
     var label = new Label() 
     { 
      Text = "name", 
      Font = Font.SystemFontOfSize(NamedSize.Default), 
      TextColor = Color.Blue 
     }; 

     var numberLabel = new Label() 
     { 
      Text = "number", 
      Font = Font.SystemFontOfSize(NamedSize.Small), 
      TextColor = Color.Black 
     }; 

     this.BindingContextChanged += (object sender, EventArgs e) => 
     { 
      var item = (KeyValuePair<string,string>)BindingContext; 
      label.SetBinding(Label.TextProperty, new Binding("Key")); 
      numberLabel.SetBinding(Label.TextProperty, new Binding("Value")); 
     }; 

     View = new StackLayout() 
     { 
      Orientation = StackOrientation.Vertical, 
      VerticalOptions = LayoutOptions.StartAndExpand, 
      Padding = new Thickness(12, 8), 
      Children = { label, numberLabel } 
     }; 
    } 
} 

Это берет адресную книгу с родной платформой (и работает отлично). То, что я пытаюсь сделать, это прочитать два свойства Text из меток в ViewCell в DataTemplate.

Есть ли способ перебрать через дочерние объекты в ViewCell, чтобы найти значения меток внутри ячейки?

ответ

0

Я предполагаю, что проблема заключается в обработчике событий MyList_ItemSelected, потому что вам передан контекст привязки для ячейки (в этом случае e.SelectedItem является ключом KeyValuePair из словаря), а не самой ячейкой?

Я не вижу способа получить ссылку на Ячейку непосредственно внутри обработчика событий.

Однако, изменив значение вашего словаря, чтобы быть классом, а не простой строки, вы можете добавить WeakReference в Cell:

public class Address 
{ 
    public string Text {get;set;} 
    public WeakReference<MyLayout> Layout { get;set;} 

    public Address (string text) 
    { 
     Text = text; 
    } 
} 

public interface IAddress 
{ 
    Dictionary<string,Address> ContactDetails(); 
} 

public MyLayout() 
{ 
    // ... Removed for brevity 

    this.BindingContextChanged += (object sender, EventArgs e) => 
    { 
     var item = (KeyValuePair<string,Address>)BindingContext; 
     label.SetBinding(Label.TextProperty, new Binding("Key")); 
     numberLabel.SetBinding(Label.TextProperty, new Binding("Value.Text")); 
     item.Value.Layout = new WeakReference<MyLayout>(this); 
    }; 

    // ... Removed for brevity 
} 

Итак, теперь значение в обработчик события будет иметь ссылка на ViewCell. Обратите внимание, что я использовал WeakReference, чтобы избежать сильного опорного цикла.

void MyList_ItemSelected (object sender, SelectedItemChangedEventArgs e) 
{ 
    var kvp = (KeyValuePair<string,Address>)e.SelectedItem; 
    var item = kvp.Value; 
    MyLayout cell; 
    item.Layout.TryGetTarget (out cell); 

    // Now that you have a reference to the ViewCell, you can access the 
    // View properties. 
} 
Смежные вопросы