- IsPullToRefreshEnabled:設為 true 啟用下拉更新
- RefreshCommand:更新邏輯
- IsRefreshing:RefreshCommand 內必須把 IsRefreshing 設為 false,更新 icon 才會消失
namespace ListViewRefresh
{
public class Product
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
public static List<Product> GetData()
{
return new List<Product>
{
new Product() { Name = "楓葉" } ,
new Product() { Name = "樹" } ,
new Product() { Name = "花" } ,
new Product() { Name = "煙火" } ,
new Product() { Name = "夜景" }
};
}
}
}
ViewModel
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace ListViewRefresh
{
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged([CallerMemberName]string PropertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
}
public ObservableCollection<Product> UpdatableSource { get; set; }
public ViewModel()
{
ObservableCollection<Product> ProdList = new ObservableCollection<Product>();
foreach (var item in Product.GetData())
{
ProdList.Add(item);
}
UpdatableSource = ProdList;
}
private bool _isRefreshing = false;
public bool IsRefreshing
{
get { return _isRefreshing; }
set
{
_isRefreshing = value;
OnPropertyChanged();
}
}
public ICommand RefreshCommand
{
get
{
return new Command(async () =>
{
await Task.Delay(2000);
UpdatableSource.Add(new Product() { Name = "植物" });
// 把 IsRefreshing 設為 false,轉圈圈的更新符號才會消失喔
IsRefreshing = false;
});
}
}
}
}
MainPage.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"
xmlns:local="clr-namespace:ListViewRefresh"
x:Class="ListViewRefresh.MainPage">
<ContentPage.BindingContext>
<local:ViewModel/>
</ContentPage.BindingContext>
<ContentPage.Content>
<StackLayout>
<ListView x:Name="lv"
ItemsSource = "{Binding UpdatableSource}"
IsPullToRefreshEnabled="True"
RefreshCommand="{Binding RefreshCommand}"
IsRefreshing="{Binding IsRefreshing}"/>
<Button x:Name="btnRefresh" Text="更新" Clicked="BtnRefresh_Clicked"></Button>
</StackLayout>
</ContentPage.Content>
</ContentPage>
MainPage.xaml.csnamespace ListViewRefresh
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void BtnRefresh_Clicked(object sender, EventArgs e)
{
lv.BeginRefresh();
}
}
}
直接點擊更新 Button 也會有下拉更新效果喔
沒有留言:
張貼留言