开始涉足Xamarin Forms。 我无法弄清楚的两件事:
我的Listview的绑定:
我有一个班级:
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并显示它。像“懒加载”之类的东西。
到目前为止,我只能弄清楚在抓取所有网址后如何设置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(),
},
};
答案 0 :(得分:3)
首先,创建一个名为 MyViewModel.cs 的视图模型类:
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
代码隐藏文件中,将视图模型设置为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");
}
}
请注意,在您的视图模型中,您需要使用ObservableCollection<T>
而不是List<T>
,因为ObservableCollection<T>
将允许ListView
自动更新无论何时添加或删除项目。
另外,为了避免一些混淆,我建议将班级名称从Mainlist
更改为MainListItem
。
答案 1 :(得分:2)
我认为你可以这样做:
mainlist.ItemsSource = new ObservableCollection<Mainlist>();
foreach (var item in yourDataFromHtmlAgilityPackScraping) {
mainlist.ItemsSource.Add(new Mainlist()
{
//scraped info from each URL
Title = item.title.ToString().Trim(),
Value = item.value.ToString().Trim(),
});
}
这里重要的部分是ObservableCollection。这允许在添加新元素时更新Listview。