我正在尝试学习应用程序开发,并且一直在阅读文档并遵循教程来熟悉。
我创建了一个包含 CollectionView 的 XAML 文件。
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Organized_Chaos.Views.NotesPage"
Title="NotesPage">
<ContentPage.Content>
<StackLayout>
<CollectionView ItemsSource ="{Binding Monkii}"
SelectionMode="Single"
SelectionChanged="OnSelectionChanged">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="10"
RowDefinitions="Auto, *"
ColumnDefinitions="Auto, *">
<Image Grid.RowSpan="2"
Source="{Binding ImageUrl}"
Aspect="AspectFill"
HeightRequest="60"
WidthRequest="60"/>
<Label Grid.Column="1"
Text="{Binding Name}"
FontAttributes="Bold"/>
<Label Grid.Row="1"
Grid.Column="1"
Text="{Binding Location}"
VerticalOptions="End"/>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
我已经制作了用数据填充 CollectionView 的相应 C# 文件:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Organized_Chaos.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class NotesPage : ContentPage
{
public IList<Monke> Monkii { get; private set; }
public NotesPage()
{
InitializeComponent();
Monkii = new List<Monke>();
Monkii.Add(new Monke
{
Name = "Baboon",
Location = "Africa & Asia",
ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Papio_anubis_%28Serengeti%2C_2009%29.jpg/200px-Papio_anubis_%28Serengeti%2C_2009%29.jpg"
});
Monkii.Add(new Monke
{
Name = "Test",
Location = "Test",
ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Papio_anubis_%28Serengeti%2C_2009%29.jpg/200px-Papio_anubis_%28Serengeti%2C_2009%29.jpg"
});
BindingContext = this;
//This would run asynchronously to continuously update the CollectionView....
Task.Run(() =>
{
int counter = 0;
counter += 1;
Thread.Sleep(1000);
Device.BeginInvokeOnMainThread(() =>
{
Monkii[0].Name = counter.ToString();
Monkii.Add(new Monke
{
Name = "Test",
Location = "Test",
ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Papio_anubis_%28Serengeti%2C_2009%29.jpg/200px-Papio_anubis_%28Serengeti%2C_2009%29.jpg"
});
});
});
}
void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
Monke selectedItem = e.CurrentSelection as Monke;
}
}
}
就目前而言,当我运行程序时,它会创建两条测试数据,如果我想要显示第三条,我必须以某种方式单击页面外并单击返回以刷新它。
但是,我希望 CollectionView 以 60 秒的时间间隔无限期更新(即,当新的股票数据进入时,您会希望在不刷新的情况下看到它),但这似乎比最初想象的要复杂得多。
为什么不使用BeginInvokeOnMainThread更新 UI ?我认为该功能是专门为此类场景设计的。