我有一個(gè)字符串列表,當(dāng)我刪除一個(gè)字符串時(shí),字符串的索引不會(huì)改變,因此當(dāng)我嘗試刪除另一個(gè)索引高于我得到的當(dāng)前數(shù)字并且錯(cuò)誤說索引超出范圍時(shí)。 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(); } }問題在我將子項(xiàng)添加到后SavedHoursLayout,然后單擊RemoveHoursLabel它會(huì)刪除當(dāng)前RemoveHoursLabel但其余的索引保持不變因此當(dāng)我單擊另一個(gè)時(shí)它會(huì)刪除分配給它的索引的子項(xiàng),如果索引超出范圍,我收到一條錯(cuò)誤消息索引超出范圍,不應(yīng)為負(fù)數(shù)或高于項(xiàng)目數(shù)。那么當(dāng)一個(gè)孩子被刪除時(shí),我如何將孩子的索引更新為當(dāng)前的索引SavedHoursLayout。
1 回答

心有法竹
TA貢獻(xiàn)1866條經(jīng)驗(yàn) 獲得超5個(gè)贊
使用 sender 獲取您希望刪除的當(dāng)前網(wǎng)格:
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);
}
- 1 回答
- 0 關(guān)注
- 91 瀏覽
添加回答
舉報(bào)
0/150
提交
取消