我试图验证每当我们将对象添加到Observable Collection中时ListView是否立即显示或刷新项目,但事实并非如此。我已经在Visual Studio的调试模式下进行了测试,并且ListView仅在所有对象都被迭代并添加到Observable集合后(例如,在下面的Subscribe方法中)显示项目。我想念什么?
注意:我还对基础模型和ViewModel(在此示例中为Page1)都应用了INotifyPropertyChanged,以便ListView也可以侦听collection的属性更改事件,但是没有运气。
这是代码示例:
public partial class Page1 : ContentPage, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
ObservableCollection<TestModel> trackListObservable;
public ObservableCollection<TestModel> Items
{
get { return trackListObservable; }
set
{
trackListObservable = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("TrackListObservable"));
}
}
}
public Page1 ()
{
InitializeComponent ();
Items = new ObservableCollection<TestModel>();
BindingContext = Items;
}
protected override void OnAppearing()
{
base.OnAppearing();
List<int> test = new List<int>() { 1, 2, 3, 4, 5 };
test.ToObservable()
.SelectMany(x => Observable.Start(() => Increment(x)))
.Select(x => x)
.Subscribe(result => Device.BeginInvokeOnMainThread(() => {
Items.Add(new TestModel() { Number = result });
}));
}
int Increment(int num)
{
return num++;
}
}
public class TestModel : INotifyPropertyChanged
{
private int number;
public int Number
{
get { return number; }
set
{
number = value;
OnPropertyChanged(nameof(Number));
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string name)
{
if (PropertyChanged == null)
return;
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
XAML:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XamarinApp.Page1"
x:Name="testpage">
<ContentPage.Content>
<StackLayout>
<ListView x:Name="testlist" HasUnevenRows="True" ItemsSource="{Binding BindingContext, Source={x:Reference testpage}}">
<ListView.ItemTemplate>
<DataTemplate>
<Label Text="{Binding Number}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Label Text="Loading Blog..." HorizontalOptions="Center" TextColor="White"/>
</StackLayout>
</ContentPage.Content>
</ContentPage>