gpt4 book ai didi

c# - Xamarin Forms - 用于延迟加载的绑定(bind) ListView

转载 作者:行者123 更新时间:2023-11-30 14:46:21 24 4
gpt4 key购买 nike

开始涉足 Xamarin Forms。两件事我想不通:

我的 ListView 的绑定(bind):

我有一个类:

    public class Mainlist
{
public string Title
{
get;
set;
}
public string Value
{
get;
set;
}

}

我的 XAML 看起来像:

   <ListView x:Name="mainlist">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<StackLayout Orientation="Vertical">
<Label Text="{Binding Title}" Font="18"></Label>
<Label Text="{Binding Value}" TextColor="Gray"></Label>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

现在发生的是我有一个 URL 列表。我从每个 URL 中使用 HTMLAgilityPack foreach 循环抓取某些信息,这工作正常。

我想在每次循环运行后将抓取的数据添加到 ListView 并显示。像“延迟加载”之类的东西。

到目前为止,我只能弄清楚如何在抓取所有 Urls 后设置 itemsource 并让它立即显示,如下所示:

 //set itemsource to URL collection
mainlist.ItemsSource = new List<Mainlist>() {
new Mainlist()
{

//scraped info from each URL
Title = title.ToString().Trim(),
Value = value.ToString().Trim(),

},
};

最佳答案

首先,创建一个名为 MyViewModel.cs 的 View 模型类:

public class MyViewModel : INotifyPropertyChanged
{
// property changed event handler
public event PropertyChangedEventHandler PropertyChanged;

private ObservableCollection<Mainlist> _list;

public ObservableCollection<Mainlist> List
{
get { return _list; }
set
{
_list = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(List)));
}
}

public MyViewModel()
{
_list = new ObservableCollection<Mainlist>();
}

public async void StartScraping()
{
// assuming you are 'awaiting' the results of your scraping method...
foreach (...)
{
await ... scrape a web page ...

var newItem = new Mainlist()
{
Title = title.ToString().Trim(),
Value = value.ToString().Trim()
};

// if you instead have multiple items to add at this point,
// then just create a new List<Mainlist>, add your items to it,
// then add that list to the ObservableCollection List.

Device.BeginInvokeOnMainThread(() =>
{
List.Add(newItem);
});
}

}
}

现在在您页面的 xaml.cs 中代码隐藏文件,将 View 模型设置为您的 BindingContext :

public class MyPage : ContentPage // (assuming the page is called "MyPage" and is of type ContentPage)
{
MyViewModel _viewModel;

public MyPage()
{
InitializeComponent();
_viewModel = new MyViewModel();
BindingContext = _viewModel;
// bind the view model's List property to the list view's ItemsSource:
mainList.setBinding(ListView.ItemsSourceProperty, "List");
}
}

请注意,在您的 View 模型中,您需要使用 ObservableCollection<T>而不是 List<T> , 作为 ObservableCollection<T>将允许 ListView每当您添加或从中删除项目时自动更新。

此外,为了减轻一点困惑,我建议将类名从 Mainlist 更改为至 MainListItem .

关于c# - Xamarin Forms - 用于延迟加载的绑定(bind) ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49420001/

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