Last active
August 29, 2015 14:27
-
-
Save ytabuchi/199b2777f6cbe8406bff to your computer and use it in GitHub Desktop.
ListViewに延々とデータを追加するサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
コチラ に正しいと思われるやり方を記載しました。。