gpt4 book ai didi

c# - 创建列表后如何更新 Xamarin Forms ListView 的 ViewCell 属性?

转载 作者:行者123 更新时间:2023-11-30 20:35:39 26 4
gpt4 key购买 nike

我希望能够更改自定义 ViewCell 上的绑定(bind)属性,并更新 ListView 项 - 但它似乎仅用于初始化 View 并且变化没有反射(reflect)出来。请告诉我我缺少什么!

在这里,我拾取了点击事件并尝试更改 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; }
}

最佳答案

我缺少的是在绑定(bind)到 ViewCell 的数据类上实现 INotifyPropertyChanged 接口(interface)。

在我最初的实现中,DocumentType 类只有简单的属性,例如 string Name { get;放; },但要将它们的值反射(reflect)在 ViewCell 中,您需要实现 INotifyPropertyChanged,以便当您更改属性时它会通知绑定(bind)的 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"); } }

...
}
}

关于c# - 创建列表后如何更新 Xamarin Forms ListView 的 ViewCell 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37699031/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com