c# - 滚动到底部时,ListView 会自动添加更多内容
问题描述
我已经ListView
在我的 xaml 页面中创建了,我正在从它的 cs 页面添加网格和按钮。当我在手机上运行它时,当我滚动listview
到底部时,后面的代码再次自动运行并再次添加相同的代码listview
。我希望这段DataTemplate
代码只为那些运行,当我向下滚动到底部时,listview
它不应该再次执行。不知道为什么它再次执行。
后面的代码
public List<AmanoraSlotsClass> AmanoraSlotsClassesList { get; set; }
public List<HadapsarSlots> HadapsarSlotClassesList { get; set; }
string SelectedLocation = null;
string SelectedDate = null;
Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
int OuterI = 0;
int innerJ = 0;
public ShowSlotsPage(string _Location, string _Date)
{
this.SelectedLocation = _Location;
this.SelectedDate = _Date;
SelectedDate = SelectedDate.Replace('/', '-');
if (SelectedLocation == "Amanora Town Park")
{
AmanoraSlotsClassesList = new List<AmanoraSlotsClass>();
}
else if (SelectedLocation == "Hadapsar Malwadi")
{
HadapsarSlotClassesList = new List<HadapsarSlots>();
}
else
{
return;
}
FetchData(SelectedLocation, SelectedDate);
InitializeComponent();
BindingContext = this;
//When i reach bottom of my listview this the control jumps to this and again adds same elements.
DataTemplate _dataTemplate = new DataTemplate(() =>
{
Grid _grid = new Grid();
_grid.RowSpacing = 50;
_grid.RowDefinitions.Add(new RowDefinition());
_grid.ColumnDefinitions.Add(new ColumnDefinition());
_grid.ColumnSpacing = 25;
if (SelectedLocation == "Amanora Town Park")
{
OuterI = AmanoraSlotsClassesList[0].GetType().GetProperties().Count();
}
for (int i = 0; i < OuterI - 1; i++)
{
if (SelectedLocation == "Amanora Town Park")
{
innerJ = AmanoraSlotsClassesList.Count();
}
for (int j = 0; j < innerJ; j++)
{
Button _but = new Button();
_but.FontSize = 10;
_but.Scale = 1;
_but.HeightRequest = 70;
if (SelectedLocation == "Amanora Town Park")
{
_but.Text = AmanoraSlotsClassesList[j].S1;
}
keyValuePairs.Add(_but.Id.ToString(), $"S{i + 1}");
// ColorDtermination(_but); //Changes color of button
Grid.SetRow(_but, j);
Grid.SetColumn(_but, i);
_grid.Children.Add(_but);
}
}
var viewCell_ = new ViewCell
{
View = _grid
};
return viewCell_;
}); ///*Till here code runs again when i scroll bottom of listview.*
_listView.ItemTemplate = _dataTemplate;
if(SelectedLocation == "Amanora Town Park")
{
_listView.ItemsSource = AmanoraSlotsClassesList;
}
}
列表视图的xaml 声明 - 列表视图的xaml 声明
解决方案
AmanoraSlotsClassesList
Xamarin.Forms ListView 为集合中的每个项目呈现项目模板。如果应用程序呈现了一个额外的项目,这意味着你的收藏有这么多项目。如果您希望列表只呈现一次模板,请确保您的列表只有一个元素。
几点建议:
- 切换到 CollectionView(更新更好)而不是 ListView
- 将项目模板移动到 Xaml 并使用基于集合元素类型的模板选择器
推荐阅读
- python - 字符串索引超出范围:IndexError
- sql - 如何从 NodeJS 连接到在 Google Cloud 上运行的 SQL 实例?
- python - Python虚拟环境激活问题
- angular - Angular Ngrx 商店 - store.select('selector name') 预计会返回书籍列表,但它返回一个不可迭代的列表
- java - 如何在执行流()之前验证列表中的字段?
- r - r ggplot 非线性渐变阿尔法
- r - C5.0 包:粘贴错误(apply(x, 1, paste, collapse = ","), collapse = "\n") : 结果将超过 2^31-1 字节
- regex - 带有反斜杠的 Spark Regex regexp_extract 错误:SQL 语句中的错误:NullPointerException
- airflow - Airflow 2.0.1 按所有者过滤 DAG
- r - 调整 x 轴上小提琴图之间的空间