2016-06-08 5 views
2

Я ожидаю, что смогу изменить связанное свойство на моем обычном ViewCell, и оно обновит пункт ListView - но оно, похоже, используется только для инициализации представления, и изменения не отражаются. Пожалуйста, скажи мне, что мне не хватает!Как обновить свойства ViewCell Xamarin Forms ListView после создания списка?

Здесь я поднимаю на повернутой события и пытаться изменить строку в ViewCell без успеха:

private void DocChooser_ItemTapped(object sender, ItemTappedEventArgs e) 
{ 
    var tappedItem = e.Item as DocumentChooserList.DocumentType; 
    tappedItem.Name = "Tapped"; // How can I change what a cell displays here? - this doesn't work 
} 

Вот мой ViewCell код:

class DocumentCellView : ViewCell 
{ 
    public DocumentCellView() 
    { 
     var OuterStack = new StackLayout() 
     { 
      Orientation = StackOrientation.Horizontal, 
      HorizontalOptions = LayoutOptions.FillAndExpand, 
     }; 

     Label MainLabel; 
     OuterStack.Children.Add(MainLabel = new Label() { FontSize = 18 }); 
     MainLabel.SetBinding(Label.TextProperty, "Name"); 

     this.View = OuterStack; 
    } 
} 

Вот мой класс ListView:

public class DocumentChooserList : ListView 
{ 
    public List<DocumentType> SelectedDocuments { get; set; } 

    public DocumentChooserList() 
    { 
     SelectedDocuments = new List<DocumentType>(); 
     this.ItemsSource = SelectedDocuments; 
     this.ItemTemplate = new DataTemplate(typeof(DocumentCellView)); 
    } 

    // My data-binding class used to populate ListView and hopefully change as we go 
    public class DocumentType 
    { 
     public string Name { get; set; } 
    } 
} 

Который я добавляю значения так:

DocChooser.SelectedDocuments.Add(new DocumentChooserList.DocumentType(){ 
    Name = "MyDoc" 
}); 

С помощью этого простого класса данных:

public class DocumentType 
{ 
    public string Name { get; set; } 
} 

ответ

3

Что я пропускаю реализует INotifyPropertyChanged интерфейс класса данных, который связан с ViewCell.

В моей первоначальной реализации класс DocumentType только имел простые свойства, как string Name { get; set; }, но иметь их значения отражены в ViewCell вам нужно сделать, реализовать INotifyPropertyChanged так, что при изменении свойства уведомляет связанный ViewCell:

public class DocumentType : INotifyPropertyChanged 
    { 
     public event PropertyChangedEventHandler PropertyChanged; 
     private void OnPropertyChanged(string nameOfProperty) 
     { 
      if (PropertyChanged != null) 
       PropertyChanged(this, new PropertyChangedEventArgs(nameOfProperty)); 
     } 

     private string _Name; 
     public string Name { get { return _Name; } set { _Name = value; OnPropertyChanged("Name"); } } 

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