我希望能够更改自定义ViewCell
上的绑定属性并更新ListView
项 - 但它似乎只用于初始化视图,并且不会反映更改。请告诉我我错过了什么!
在这里,我选择了tapped事件并尝试更改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; }
}
答案 0 :(得分:4)
我缺少的是在绑定到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"); } }
...
}
}