2016-06-08 77 views
2

我希望能夠更改我的自定義ViewCell上的綁定屬性,並且它將更新ListView項目 - 但它似乎只用於初始化視圖並且不會反映更改。請告訴我我錯過了什麼!如何在創建列表後更新Xamarin表單ListView的ViewCell屬性?

在這裏,我拿起了竊聽事件並試圖改變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

什麼,我缺的是執行上綁定到ViewCell數據類INotifyPropertyChanged接口。

我在原來的實現中,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"); } } 

     ... 
    } 
} 
相關問題