开始涉猎Xamarin形式. 我无法弄清的两件事:
我的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循环抓取某些信息,效果很好.
我想在每次循环运行后将抓取的数据添加到列表视图中,并显示它.类似于"延迟加载".
到目前为止,我只能弄清楚在刮掉所有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 的视图模型类:
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.
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有