[英]Get Current IndexOf Children In List
I have a list of strings,when I remove one the indexof the strings do not change hence when I try removing another with the index higher than the current number I get and error saying the index in out of range.我有一个字符串列表,当我删除一个字符串时,字符串的索引不会改变,因此当我尝试删除另一个索引高于当前数字的字符串时,我得到的错误是索引超出范围。
public class MyClass{
public StackLayout SavedHoursLayout = new StackLayout {};
public Label RemoveHoursLabel;
public TapGestureRecognizer RemoveTapped;
public Grid HoursRemoveGrid;
public Button AddHoursButton = new Button();
public MyClass()
{
Content = new StackLayout
{
Children = { AddHoursButton,SavedHoursLayout }
}
AddHoursButton.Clicked+=AddHoursButton_Clicked;
AddSavedHours();
}
public void AddSavedHours()
{
Label Time = new Label { };
RemoveHoursLabel = new Label { Text="remove",TextColor=Color.Red,FontAttributes=FontAttributes.Italic};
HoursRemoveGrid = new Grid();
RemoveTapped = new TapGestureRecognizer();
this.BindingContext = HoursRemoveGrid;
HoursRemoveGrid.Children.Add(Time,0,0);
HoursRemoveGrid.Children.Add(RemoveHoursLabel,1,0);
SavedHoursLayout.Children.Add(HoursRemoveGrid);
RemoveHoursLabel.GestureRecognizers.Add(RemoveTapped);
RemoveTapped.Tapped += RemoveTapped_Tapped;
void RemoveTapped_Tapped(object sender, EventArgs e)
{
int position = SavedHoursLayout.Children.IndexOf(HoursRemoveGrid);
SavedHoursLayout.Children.RemoveAt(position);
}
}
private void AddHoursButton_Clicked(object sender, System.EventArgs e)
{
AddSavedHours();
}
}
Question题
after I add children to the SavedHoursLayout
, and click on the RemoveHoursLabel
it removes the current RemoveHoursLabel
but the index of the rest remain the same hence when i click on another one it remove the child with the index assigned to it and if the index is out of bounds , I get an error saying在我将子项添加到
SavedHoursLayout
并单击RemoveHoursLabel
它会删除当前的RemoveHoursLabel
但其余的索引保持不变,因此当我单击另一个索引时,它会删除分配给它的索引的子项,如果索引已失效的界限,我得到一个错误说
index is out of range,should not be negative or above the number of items.
索引超出范围,不应为负数或大于项目数。
so how do I update the index of the children to the current one when a child is removed of the SavedHoursLayout
changes.那么当孩子从
SavedHoursLayout
更改中移除时,如何将孩子的索引更新为当前的索引。
Use the sender to obtain the current grid that you wish to remove:使用发件人获取您要删除的当前网格:
void RemoveTapped_Tapped(object sender, EventArgs e)
{
var grid = (sender as Label).Parent as Grid;
int position = SavedHoursLayout.Children.IndexOf(grid);
SavedHoursLayout.Children.RemoveAt(position);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.