Skip to content

Instantly share code, notes, and snippets.

@ytabuchi
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ytabuchi/199b2777f6cbe8406bff to your computer and use it in GitHub Desktop.
Save ytabuchi/199b2777f6cbe8406bff to your computer and use it in GitHub Desktop.
ListViewに延々とデータを追加するサンプル
// ItemsSource に ObservableCollection を使用すると Collection を更新するだけで自動的に ListView の表示も更新してくれます。
// これは ListView の ItemsSource に List<T> を使用した場合の悪例です。
// List を更新しても ListView の表示が更新されないため、手動で ItemsSource と ItemTemplate を再指定する必要があります。
// 標準の TextCell を new DataTemplate(typeof(TextCell)) してしまうと都度 SetBinding もしないといけないので、MyTextCell に SetBinding を内包しました。。
// 正しいやり方を
// http://ytabuchi.hatenablog.com/entry/2015/08/12/010522
// に記載しました。
class MainPageCS : ContentPage
{
List<ListItem> listItems = new List<ListItem>();
int n = 0;
const int cellAmount = 25;
public MainPageCS()
{
AddListItem(n);
var list = new ListView
{
ItemsSource = listItems,
ItemTemplate = new DataTemplate(typeof(MyTextCell)),
};
list.ItemAppearing += (object sender, ItemVisibilityEventArgs e) => {
if (listItems.Last() == e.Item as ListItem)
{
n++;
listItems = AddListItem(cellAmount * n);
// ItemsSource と ItemTemplate を再指定しています。。
list.ItemsSource = listItems;
list.ItemTemplate = new DataTemplate(typeof(MyTextCell));
}
};
Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);
Content = list;
}
List<ListItem> AddListItem(int i) {
foreach (var j in Enumerable.Range(i , cellAmount))
{
listItems.Add(new ListItem{ TextItem = "TextData " + j, DetailItem = "DetailData " + j });
}
return listItems;
}
}
class MyTextCell : TextCell
{
public MyTextCell()
{
this.SetBinding(TextCell.TextProperty, "TextItem");
this.SetBinding(TextCell.DetailProperty, "DetailItem");
}
}
class ListItem
{
public string TextItem { get; set; }
public string DetailItem { get; set; }
}
@ytabuchi
Copy link
Author

コチラ に正しいと思われるやり方を記載しました。。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment